1

Say I have a list composed of a number of lists of two items each:

a = [[14, 0.5], [12, 0.8], [22, 0.6], [15, 0.2], [17, 0.5], [18, 0.4]]

I need to reorder this list first according to the second items inside each list from max to min and then according to the first items from min to max.

I know how to reorder a list according to two items using the second item first and the first item second:

b = sorted(a, key=lambda item:(item[1], item[0]))
b = [[15, 0.2], [18, 0.4], [14, 0.5], [17, 0.5], [22, 0.6], [12, 0.8]]

but this returns a list ordered from min to max for both items, which is not what I need.

This is what b should look like:

b = [[12, 0.8], [22, 0.6], [14, 0.5], [17, 0.5], [18, 0.4], [15, 0.2]]
4

2 回答 2

6

您可以使用负值:

b = sorted(a, key=lambda item:(-item[1], item[0]))
于 2013-07-30T13:31:48.430 回答
4

只需反向使用您想要的项目的否定:

>>> b = sorted(a, key=lambda item:(-item[1], item[0]))
>>> b
[[12, 0.8], [22, 0.6], [14, 0.5], [17, 0.5], [18, 0.4], [15, 0.2]]
于 2013-07-30T13:31:55.830 回答