尝试排序整数但出现 'invalid literal for int() with base 10' 错误

0 投票
2 回答
2113 浏览
提问于 2025-04-16 11:14

我正在尝试通过第八列来对一个列表进行排序(在分割文件之后),但是我一直遇到这个错误:

ValueError: invalid literal for int() with base 10: '72912,'

这是我想要排序的列表:

UDP outside 192.168.30.33:1046 inside 192.168.84.28:161, idle 0:00:18, bytes 72912, flags  
TCP outside 192.168.120.26:1339 inside 192.168.84.17:445, idle 5:29:24, bytes 19305, flags  
TCP outside 192.168.120.26:1271 inside 192.168.84.161:139, idle 5:29:41, bytes 4346, flags  
TCP outside 192.168.120.60:1955 inside 192.168.84.100:445, idle 3:56:40, bytes 259388, flags  
TCP outside 192.168.120.60:1951 inside 192.168.84.17:445, idle 3:56:40, bytes 257120, flags   
TCP outside 192.168.120.60:1940 inside 192.168.84.161:139, idle 3:56:57, bytes 260372, flags  
TCP outside 192.168.120.49:1324 inside 192.168.84.161:445, idle 5:04:12, bytes 2705, flags

这是我的Python脚本:

lines = open("home/file.txt", "r").readlines() 
lines = [x.split() for x in lines] 
lines.sort(cmp, key=lambda x:int(x[8]), reverse=True) 
for i in lines: 
    print i 

非常感谢任何帮助...

2 个回答

2

你想把的那个数字转换成整数,但它里面有一个逗号。所以,在你的代码中,应该用下面的方式来处理:

lines.sort(cmp, key=lambda x:int(x[8]), reverse=True) 

试试这样做

lines.sort(cmp, key=lambda x:int(x[8].strip(',')), reverse=True) 
4

在你尝试把这个列的数据转换成整数之前,里面有一个多余的逗号,你需要把它去掉。

lines.sort(cmp, key=lambda x:int(x[8][:-1]), reverse=True)

这样做会有很大的不同。

In [1]: foo = '72912,'
In [2]: int(foo)
ValueError: invalid literal for int() with base 10: '72912,'

In [3]: int(foo[:-1])
Out[3]: 72912

撰写回答