I have a list with ~10^6 tuples in it like this:
[(101, 153), (255, 827), (361, 961), ...]
^ ^
X Y
I want to find the maximum value of the Y
s in this list, but also want to know the X
that it is bound to.
How do I do this?
operator.itemgetter()
:
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis, key=itemgetter(1)) # Faster solution
Out[82]: (361, 961)
In [83]: max(lis, key=itemgetter(1))[0] # Faster solution
Out[83]: 361
lambda
:
In [54]: max(lis, key=lambda item: item[1])
Out[54]: (361, 961)
In [55]: max(lis, key=lambda item: item[1])[0]
Out[55]: 361
timeit
comparison of operator.itemgetter
vs lambda
:
In [84]: %timeit max(lis, key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [85]: %timeit max(lis, key=lambda item: item[1])
1000 loops, best of 3: 556 us per loop