Python行排序

2024-10-04 09:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几点:

line  = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777',,'aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']

有没有别的地方我可以按(鲍勃、拉里、史蒂夫)再按(11112222)排序?你知道吗

所以。。。你知道吗

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'

Tags: infor排序地方linestevesplitbob
1条回答
网友
1楼 · 发布于 2024-10-04 09:29:44

将拆分留给键函数:

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']

如果你的“行”没有像逗号+空格那样整齐地分开,你可能也需要去掉空白。你知道吗

相关问题 更多 >