简体   繁体   English

Python二级索引排序列表,多个列表中的键

[英]Python secondary sorting list of index, key from multiple lists

I am trying to perform a secondary sorting with list.sort() , and here is my code: 我正在尝试使用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)

The result was [3, 4, 5, 6, 7, 8, 0, 1, 2, 9, 10, 11] , while I expected the last three items to be [..., 10, 9, 11] . 结果是[3, 4, 5, 6, 7, 8, 0, 1, 2, 9, 10, 11] ,而我希望最后三个项目是[..., 10, 9, 11]

I thought it should do secondary sorting (based on the value of b_list ), but seems that it didn't. 我认为它应该进行二级排序(基于b_list的值),但似乎没有。


EDIT: typo fixed. 编辑:错字固定。

You could do: 您可以这样做:

index_list.sort(key=lambda x:(a_list[x], -b_list[x])) # because -3 < 2 and by default it sorts in ascending order

Output 产量

[3, 4, 5, 6, 7, 8, 0, 1, 2, 10, 9, 11]

You should use: 您应该使用:

index_list.sort(key=lambda x:(a_list[x], -b_list[x]))

instead of 代替

index_list.sort(key=lambda x:(a_list[x], b_list[x]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM