[英]How to have primary and secondary sorting stipulations for a list of lists in Python
[英]Python secondary sorting list of index, key from multiple lists
我正在尝试使用list.sort()
进行二级排序,这是我的代码:
index_list = list(range(12))
a_list = [5, 5, 5, 1, 2, 3, 3, 3, 3, 8, 8, 10]
b_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 10]
index_list.sort(key=lambda x:(a_list[x], b_list[x]))
print(index_list)
结果是[3, 4, 5, 6, 7, 8, 0, 1, 2, 9, 10, 11]
,而我希望最后三个项目是[..., 10, 9, 11]
。
我认为它应该进行二级排序(基于b_list
的值),但似乎没有。
编辑:错字固定。
您可以这样做:
index_list.sort(key=lambda x:(a_list[x], -b_list[x])) # because -3 < 2 and by default it sorts in ascending order
产量
[3, 4, 5, 6, 7, 8, 0, 1, 2, 10, 9, 11]
您应该使用:
index_list.sort(key=lambda x:(a_list[x], -b_list[x]))
代替
index_list.sort(key=lambda x:(a_list[x], b_list[x]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.