简体   繁体   English

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

[英]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 它假设一个事实是

  1. Tuples are compared lexicographic-ally based on indexes 根据索引在字典上比较元组

    See doc : 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. 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.

相关问题 在元组列表中的元组子集中查找第二个绝对值的最小值(python) - Find minimum of absolute of second value in a subset of tuples in a list of tuples (python) 如何找到列表中最大和最小数字的位置? - How to find the position of the maximum and minimum number in a list? 时间序列数据的交叉验证:将用户定义的具有列表内部列表的元组列表转换为用于在 GridSearchCV 中应用的元组列表 - Cross-validation for time-series data: Convert user-defined list of tuples with inner lists of lists to list of tuples for applying in GridSearchCV 如何找到python用户定义类的属性? - How to find attributes of a python user-defined class? 如何用Matploblib用户定义的颜色图找到白色? - How to find the color white with Matploblib user-defined colormap? 如何找到用户定义范围内的所有素数? - How do I find all primes in a user-defined range? 如何使用 Python 列表创建用户定义的 function? - How to create user-defined function with Python list? 如何在 Python 中创建用户定义的列表? - How do I create a user-defined list in Python? 如何在元组列表中找到第一次的最大绝对索引? - How to find the index of the maximum absolute of the first time in a list of tuples? 在熊猫中找到用户定义的窗口的平均值 - Find the average for user-defined window in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM