简体   繁体   中英

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:

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] .

I thought it should do secondary sorting (based on the value of b_list ), but seems that it didn't.


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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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