开发者

Advanced sorting criteria for a list of nested tuples

开发者 https://www.devze.com 2023-01-18 01:08 出处:网络
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

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

精彩评论

暂无评论...
验证码 换一张
取 消