[英]Python Line Sorting -
我有以下幾點:
line = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777',,'aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']
我可以按(Bob,Larry,Steve)排序,然后按(1111,2222)排序嗎?
所以...
for i in line:
i = i.split(' ')
pos1 = i[0]
pos2 = i[1]
pos3 = i[2]
pos4 = i[3]
所以我需要按pos3排序,然后按pos2排序。
所需的輸出為:
'aaaa, 1111, BOB, 7777'
'aaaa, 1111, BOB, 8888'
'BBBB, 2222, BOB, 7777'
'aaaa, 1111, larry, 7777'
'aaaa, 1111, Steve, 8888'
將拆分留給關鍵功能:
sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1])
這將返回在串line
詞典的順序,不區分大小寫。 [2:0:-1]
片以相反的順序返回第三和第二列。
演示:
>>> line = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777','aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']
>>> from pprint import pprint
>>> pprint(sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1]))
['aaaa, 1111, BOB, 7777',
'aaaa, 1111, BOB, 8888',
'BBBB, 2222, BOB, 7777',
'aaaa, 1111, larry, 7777',
'aaaa, 1111, Steve, 8888']
如果您的“行”沒有用逗號和空格隔開,那么您可能還需要去除空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.