嵌套元组列表的高级排序标准 [英] Advanced sorting criteria for a list of nested tuples

查看:140
本文介绍了嵌套元组列表的高级排序标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的嵌套元组列表:

I have a list of nested tuples of the form:

[(a, (b, c)), ...]

现在,我想选择最大化 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))]

获胜者应该是

(7, (4, 1))

感谢您的帮助.

推荐答案

据我所知,您想按a降序排列,然后按b升序排列,然后按c升序排列.如果是的话,您可以这样做:

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.

如果将b和c求和,则在我的示例中,它将简单地为sum(x[1])而不是x[1].

If b and c should be summed up, it would simply be sum(x[1]) instead of x[1] in my example.

我的键函数返回一个元组,因为Python正确地对包含多个元素的元组进行了排序:

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

这篇关于嵌套元组列表的高级排序标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆