嵌套元组列表的高级排序标准
我有一个以下形式的嵌套元组列表:
[(a, (b, c)), ...]
现在我想选择最大化 a 同时最小化 b 和 c 的元素同一时间。例如,
[(7, (5, 1)), (7, (4, 1)), (6, (3, 1))]
获胜者应该是
(7, (4, 1))
任何帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的理解,您希望按 a 降序排序,按 b 升序排序,然后按 c 升序排序。如果这是正确的,您可以这样做:
选择“获胜者”就像选择第一个元素一样简单。
如果应该将 b 和 c 相加,则在我的示例中,它只是
sum(x[1])
而不是x[1]
。我的 key 函数返回一个元组,因为 Python 正确地对包含多个元素的元组进行了排序:
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:
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 ofx[1]
in my example.My key function returns a tuple because Python correctly sorts tuples containing multiple elements: