嵌套元组列表的高级排序标准

发布于 2024-09-25 17:23:31 字数 276 浏览 0 评论 0原文

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

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

现在我想选择最大化 a 同时最小化 bc 的元素同一时间。例如,

[(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

意中人 2024-10-02 17:23:31

根据我的理解,您希望按 a 降序排序,按 b 升序排序,然后按 c 升序排序。如果这是正确的,您可以这样做:

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

选择“获胜者”就像选择第一个元素一样简单。

如果应该将 b 和 c 相加,则在我的示例中,它只是 sum(x[1]) 而不是 x[1]

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

>>> sorted([(1,2), (1,1), (1,-1), (0,5)])
[(0, 5), (1, -1), (1, 1), (1, 2)]

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)]
面犯桃花 2024-10-02 17:23:31
>>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))
(7, (4, 1))
>>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))
(7, (4, 1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文