I have a list of IPs and integers that I'd like to python to sort by the 4th column:
172.2.174.86 172.2.15.65 69694 42272874
172.2.200.100 172.2.15.20 14 4326
10.1.162.12 172.2.15.162 4741 170676
172.2.174.86 172.2.15.64 46021 33956341
10.1.167.237 172.2.15.69 921 133574
The problem is Python can't seem to handle IP addresses and integers in the same list. I can only sort alphabetically. How do I do correct sorting based开发者_如何学Go on the value of the 4th column Here's what I have:
lines = open("file.txt", "r").readlines()
lines=[x.split() for x in lines]
for i in lines:
i.reverse()
lines.sort(cmp, reverse=True)
for i in lines:
print i
Is the following what you're after?
lines = open("file.txt", "r").readlines()
lines = [x.split() for x in lines]
lines.sort(cmp, key=lambda x:int(x[3]))
for i in lines:
print i
import csv
with open("file.txt") as f:
data = list(csv.reader(f, delimiter=' '))
def intkey(row):
return int(row[3])
data.sort(key=intkey, reverse=True)
print data
the results:
[['172.2.174.86', '172.2.15.65', '69694', '42272874'],
['172.2.174.86', '172.2.15.64', '46021', '33956341'],
['10.1.162.12', '172.2.15.162', '4741', '170676'],
['10.1.167.237', '172.2.15.69', '921', '133574'],
['172.2.200.100', '172.2.15.20', '14', '4326']]
you ip integers are stored in string, right? and the 4th column is part of the string? however you can do something like
l.sort(key=lambda x:x.split()[3], reverse=True)
or if you want more control, you can define a function that takes 2 string and determine wich is the highest, then pass that func to sort through cmp argument
lines = open("file.txt", "r").readlines()
lines=[x.split() for x in lines]
lines.sort(key=lambda l: int(l[3]), reverse=True)
I don't think you need to reverse your lines. You should be able to simply sort the lines using
lines.sort( lambda x, y: cmp( int(x[3]), int(y[3]) ) )
assuming that you always have an integral value in your fourth column.
Good link discussing Python sequences and how to manipulate them: Effbot
I couldnt find clean easy way to do this in py w/o long complex functions and lambdas,
easiest way by far,
pip install sh
from sh import sort
sort('-nr', '/tmp/file1', '-o', '/tmp/file1')
sh module is fantastic.
精彩评论