[英]How to find user-defined minimum and maximum value in a list of tuples
I have a list of tuples with 2 integers each: 我有一个元组列表,每个元组都有2个整数:
a_list=[(20, 1), (16, 0), (21, 0), (20, 0), (24, 0), (25, 1)]
What I am looking for is a way to find and return the tuple that has the smallest second item with the biggest first item. 我正在寻找的是一种找到并返回第二项最小,第一项最大的元组的方法。 In the above list, it will be the tuple
(24, 0)
. 在上面的列表中,它将是元组
(24, 0)
。
Your example is trivial enough for the following approach to work 您的示例足以使以下方法正常工作
>>> 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)
It assumes the fact that 它假设一个事实是
Tuples are compared lexicographic-ally based on indexes 根据索引在字典上比较元组
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
这意味着要比较相等,每个元素都必须比较相等,并且两个序列必须具有相同的类型且长度相同
Ordering of numbers revereses on change of sign 数字的顺序反映符号的变化
This works: 这有效:
>>> a_list = [(20, 1), (16, 0), (21, 0), (20, 0), (24, 0), (25, 1)]
>>> a = min(x[1] for x in a_list)
>>> max(b for b in a_list if b[1] == a)
(24, 0)
>>>
Assuming that my understanding is correct, then here's what you need to do. 假设我的理解是正确的,那么这就是您需要做的。
Find the minimum second value: 找到最小的第二个值:
lowest = min(a_list, key=lambda t: t[1])[1]
Then find all the items that have that as the second item 然后找到所有具有第二个项目的项目
having_lowest = filter(lambda t: t[1] == lowest, a_list)
Then find the one with the highest first number 然后找到第一个数字最高的那个
having_max = max(having_lowest, key=lambda t: t[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.