我正在尝试按第8列排序列表(拆分文件后)但是我一直收到此错误:
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
任何帮助都非常感谢...
答案 0 :(得分: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
答案 1 :(得分:2)
您尝试转换为int的数字为','。所以,在你的代码而不是
lines.sort(cmp, key=lambda x:int(x[8]), reverse=True)
试
lines.sort(cmp, key=lambda x:int(x[8].strip(',')), reverse=True)