[英]Getting the correct max value from a list of tuples
我的元组列表如下所示:
[(0, 0), (3, 0), (3, 3), (0, 3), (0, 0), (0, 6), (3, 6), (3, 9), (0, 9), (0, 6), (6, 0), (9, 0), (9, 3), (6, 3), (6, 0), (0, 3), (3, 3), (3, 6), (0, 6), (0, 3)]
它的格式为 (X, Y),我想在此列表中获取所有 X 和 Y 的最大值和最小值。
应该是 min(X)=0, max(X)=9, min(Y)=0, max(Y)=9
但是,当我这样做时:
min(listoftuples)[0], max(listoftuples)[0]
min(listoftuples)[1], max(listoftuples)[1]
...对于 Y 值,显示的最大值为 3,这是不正确的。
这是为什么?
对于 Y 值,显示的最大值为 3
因为max(listoftuples)
返回元组(9, 3)
,所以max(listoftuples)[0]
是9
而max(listoftuples)[1]
是3
。
默认情况下,iterables 根据第一个索引的值进行排序/比较,然后是第二个索引的值,依此类推。
如果要在第二个索引中找到最大值的元组,则需要使用key
function:
from operator import itemgetter
li = [(0, 0), (3, 0), ... ]
print(max(li, key=itemgetter(1)))
# or max(li, key=lambda t: t[1])
输出
(3, 9)
这是使用列表推导的一种简单方法:
min([arr[i][0] for i in range(len(arr))])
max([arr[i][0] for i in range(len(arr))])
min([arr[i][1] for i in range(len(arr))])
max([arr[i][1] for i in range(len(arr))])
在这段代码中,我使用列表推导来创建所有 X 和所有 Y 值的列表,然后找到每个列表的最小值/最大值。 这会产生您想要的答案。
前两行用于 X 值,最后两行用于 Y 值。
元组按它们的第一个值排序,然后在平局的情况下,按它们的第二个值排序(依此类推)。 这意味着max(listoftuples)
是(9, 3)
。 请参阅Python 中的元组比较如何工作?
因此,要找到最高的 y 值,您必须专门查看元组的第二个元素。 一种方法是将列表拆分为 x 值和 y 值,如下所示:
xs, ys = zip(*listoftuples)
或者,如果您发现这令人困惑,您可以改用它,这大致等效:
xs, ys = ([t[i] for t in listoftuples] for i in range(2))
然后获取他们的每个最小值和最大值,如下所示:
x_min_max, y_min_max = [(min(L), max(L)) for L in (xs, ys)]
print(x_min_max, y_min_max) # -> (0, 9) (0, 9)
另一种方法是使用NumPy将listoftuples
视为矩阵。
import numpy as np
a = np.array(listoftuples)
x_min_max, y_min_max = [(min(column), max(column)) for column in a.T]
print(x_min_max, y_min_max) # -> (0, 9) (0, 9)
(可能有一种更惯用的方法来做到这一点,但我对 NumPy 不是很熟悉。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.