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.
答案 0 :(得分:2)
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]
答案 1 :(得分:0)
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]))