Advanced sorting criteria for a list of nested tuples

蓝咒 提交于 2019-12-19 04:40:55

问题


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, 1))

Any help is appreciated.


回答1:


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



回答2:


>>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))
(7, (4, 1))


来源:https://stackoverflow.com/questions/3831449/advanced-sorting-criteria-for-a-list-of-nested-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!