gpt4 book ai didi

python - 如何在元组列表中查找用户定义的最小值和最大值

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:25 26 4
gpt4 key购买 nike

我有一个元组列表,每个元组有 2 个整数:

a_list=[(20, 1), (16, 0), (21, 0), (20, 0), (24, 0), (25, 1)]

我正在寻找的是一种查找并返回具有最小第二项和最大第一项的元组的方法。在上面的列表中,它将是元组 (24, 0)

最佳答案

您的示例对于以下方法来说足够简单

>>> a_list=[(20, 1), (16, 0), (21, 0), (20, 0), (24, 0), (25, 1)]
>>> max(a_list, key=lambda e:(-e[-1],e[0]))
(24, 0)

假设

  1. 元组根据索引进行字典顺序比较

    参见 doc :

    Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length

  2. 数字的顺序随着符号的改变而反转

关于python - 如何在元组列表中查找用户定义的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com