[英]Sort a 2D list by two fields
Suppose I have a 2D list:假设我有一个二维列表:
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'])
I would like to sort this 2d list by the fourth and fifth columns.我想按第四列和第五列对这个二维列表进行排序。 I'd like column 4 to be sorted ascending, but column 5 to be in order of New, Active, Closed.
我希望第 4 列按升序排序,但第 5 列按“新建”、“活动”、“已关闭”的顺序排列。
Desired 2d list:所需的二维列表:
[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'])
This line gets me close, but not quite:这条线让我很接近,但不完全是:
sortedData = sorted(data, key=lambda x:(x[3],x[4]))
Any suggestions on sorting by two fields?关于按两个字段排序的任何建议?
You can construct a dictionary priority mapping and then use a tuple
sort key:您可以构建字典优先级映射,然后使用
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.