Reputation: 1436
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.
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)
Upvotes: 2
Views: 1056
Reputation: 24582
You could use index
method of the list object with max
function. 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.
ie, listTuples.index((5, 10))
Upvotes: 6
Reputation: 1039
I would recommend using max()
function:
x = [abs(j - i) for i, j in listTuples]
print(x.index(max(x)))
Upvotes: 2
Reputation: 13393
you can use the builtin max
with a custom key function, like this:
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.
Upvotes: 1
Reputation: 15035
Use max()
with a custom key:
max(enumerate(listTuples), key = lambda x: x[1][1]-x[1][0])[0]
Upvotes: 3