简体   繁体   中英

Trying to sort integers but getting 'invalid literal for int() with base 10' error

I'm trying to sort a list by the 8th column (after splitting the file) BUT I keep getting this error:

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

Here is my list I'm trying to sort:

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

Here's my Python script:

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 

Any help is really appreciated with this...

There is a trailing comma in the column you need to remove before trying to convert it to an integer.

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

That makes a difference.

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

The number which you are trying convert to int has a ','. So, in your code instead of

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

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM