[英]From a list of tuples get the tuple with the largest difference between its elements
Suppose I have a list of tuples like: 假设我有一个元组列表,如:
listTuples = [(0, 3), (5, 10), (2, 4)]
I want to get the index of the tuple with the largest difference between the tuple elements 我想得到元组的索引与元组元素之间的最大差异
3 - 0 = 3
10 - 5 = 5
4 - 2 = 2
So I want 1 as return. 所以我想要1作为回报。
Currently I am doing the following but perhaps there is a better way (faster, fewer lines of code) to do it. 目前我正在做以下事情,但也许有更好的方法(更快,更少的代码行)来做到这一点。
listTuples = [(0, 3), (5, 10), (2, 4)]
k = 0
e = 0
for j, i in enumerate(listTuples):
diff = i[1] - i[0]
if k < diff:
k = diff
e = j
else:
pass
print(e)
You could use index
method of the list object with max
function. 您可以使用具有
max
函数的列表对象的index
方法。 ie, 即
>>> listTuples = [(0, 3), (5, 10), (2, 4)]
>>> listTuples.index(max(listTuples, key=lambda x: x[1] - x[0]))
1
Here max(listTuples, key=lambda x: x[1] - x[0])
will return a tuple that has maximum difference and index
method will find the index of this tuple from the original list. 这里
max(listTuples, key=lambda x: x[1] - x[0])
将返回一个具有最大差异的元组, index
方法将从原始列表中找到该元组的索引。
ie, listTuples.index((5, 10))
即
listTuples.index((5, 10))
将max()
与自定义键一起使用:
max(enumerate(listTuples), key = lambda x: x[1][1]-x[1][0])[0]
I would recommend using max()
function: 我建议使用
max()
函数:
x = [abs(j - i) for i, j in listTuples]
print(x.index(max(x)))
you can use the builtin max
with a custom key function, like this: 你可以使用带有自定义键功能的builtin
max
,如下所示:
max(range(len(listTuples)), key=lambda i: listTuples[i][1] - listTuples[i][0])
It gives a value from range(len(listTuples))
, based on the maximum value returned for each element from the key
function. 它根据从
key
函数返回的每个元素的最大值,给出range(len(listTuples))
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.