[英]How can I enhance this python code to do a natural sort of a list of FQN hostnames and ip addresses?
[英]How can I sort IP addresses and integers in Python?
我有一个IP和整数列表,我想用python按第四列进行排序:
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
问题是Python似乎无法在同一列表中处理IP地址和整数。 我只能按字母顺序排序。 如何根据第4列的值进行正确的排序这是我所拥有的:
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
以下是您所追求的?
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
结果:
[['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']]
ip整数存储在字符串中,对不对? 第四列是字符串的一部分? 但是你可以做类似的事情
l.sort(key=lambda x:x.split()[3], reverse=True)
或者,如果您想要更多控制权,则可以定义一个函数,该函数使用2个字符串并确定wich是最高的,然后将该函数传递给cmp参数进行排序
lines = open("file.txt", "r").readlines()
lines=[x.split() for x in lines]
lines.sort(key=lambda l: int(l[3]), reverse=True)
我认为您不需要扭转局面。 您应该能够使用
lines.sort( lambda x, y: cmp( int(x[3]), int(y[3]) ) )
假设您在第四栏中始终有一个整数值。
讨论Python序列以及如何操作它们的良好链接: Effbot
我找不到在py中没有复杂函数和lambda的简单简便方法,
到目前为止最简单的方法
点安装sh
from sh import sort
sort('-nr', '/tmp/file1', '-o', '/tmp/file1')
sh模块太棒了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.