按两个字段对二维列表排序

2024-09-25 16:30:39 发布

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

假设我有一个2D列表:

data = []
data.append([7, 12, 19, 'Type1', 'New'])
data.append([1, 2, 21, 'Type3', 'New'])
data.append([12, 7, 22, 'Type2', 'Active'])
data.append([3, 0, 22, 'Type3', 'Active'])
data.append([0, 1, 18, 'Type2', 'Closed'])
data.append([13, 11, 19, 'Type1', 'Closed'])

我想按第四列和第五列对这个2d列表进行排序。我希望第4列按升序排序,但第5列按新的、活动的、关闭的顺序排序

所需2d列表:

[7, 12, 19, 'Type1', 'New'])
[13, 11, 19, 'Type1', 'Closed'])
[12, 7, 22, 'Type2', 'Active'])
[0, 1, 18, 'Type2', 'Closed'])
[1, 2, 21, 'Type3', 'New'])
[3, 0, 22, 'Type3', 'Active'])

这句话让我很接近,但不完全是:

sortedData = sorted(data, key=lambda x:(x[3],x[4]))

对按两个字段排序有什么建议吗


Tags: key列表newdata排序顺序activesorted
1条回答
网友
1楼 · 发布于 2024-09-25 16:30:39

您可以构造字典优先级映射,然后使用tuple排序键:

priorities = {v: k for k, v in enumerate(['New', 'Active', 'Closed'])}

res = sorted(data, key=lambda x: (x[3], priorities[x[4]]))

print(res)

[[7, 12, 19, 'Type1', 'New'],
 [13, 11, 19, 'Type1', 'Closed'],
 [12, 7, 22, 'Type2', 'Active'],
 [0, 1, 18, 'Type2', 'Closed'],
 [1, 2, 21, 'Type3', 'New'],
 [3, 0, 22, 'Type3', 'Active']]

相关问题 更多 >