![](/img/trans.png)
[英]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.