Advanced sorting criteria for a list of nested tuples
I have a list of nested tuples of the form:
[(a, (b, c)), ...]
Now I would like to pick the element which maximizes a while minimizing b and c at the same time. For example in
[(7, (5, 1)), (7, (4, 1)), (6, (3, 1))]
the winner should be
(7, (4开发者_C百科, 1))
Any help is appreciated.
In my understanding, you want to sort decreasingly by a, and ascendingly by b, then by c. If that's right, you can do it like so:
>>> l=[(7, (5, 1)), (7, (4, 1)), (6, (3, 2)), (6, (3, 1))]
>>> sorted(l, key = lambda x: (-x[0], x[1]))
[(7, (4, 1)), (7, (5, 1)), (6, (3, 1)), (6, (3, 2))]
Picking the "winner" would be as simple as picking the first element.
If b and c should be summed up, it would simply be sum(x[1])
instead of x[1]
in my example.
My key function returns a tuple because Python correctly sorts tuples containing multiple elements:
>>> sorted([(1,2), (1,1), (1,-1), (0,5)])
[(0, 5), (1, -1), (1, 1), (1, 2)]
>>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))
(7, (4, 1))
精彩评论