Python行排序 -

Try*_*ard 1 python sorting

我有以下内容:

line  = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777',,'aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']
Run Code Online (Sandbox Code Playgroud)

在那里我可以排序(鲍勃,拉里,史蒂夫)然后(1111,2222)?

所以...

for i in line:
    i = i.split(' ')
    pos1 = i[0]
    pos2 = i[1]
    pos3 = i[2]
    pos4 = i[3]
Run Code Online (Sandbox Code Playgroud)

所以我需要按pos3然后按pos2排序.

期望的输出将是:

'aaaa, 1111, BOB, 7777'
'aaaa, 1111, BOB, 8888'
'BBBB, 2222, BOB, 7777'
'aaaa, 1111, larry, 7777'
'aaaa, 1111, Steve, 8888'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

将拆分保留为关键功能:

sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1])
Run Code Online (Sandbox Code Playgroud)

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']
Run Code Online (Sandbox Code Playgroud)

如果你的'line'不是那么整齐的逗号+空格分隔,你可能也需要去掉空格.