theguyty theguyty - 1 year ago 74
Python Question

Python - Selecting smallest y from a list of tuples and keeping x

I am trying to iterate through a list of tuples like this:

[(0, 0.0083553666846612491), (1, 0.0054999681509501821)]

and find the smallest value on the right hand side of the tuple and then save the accompanying left hand side value to a variable.

What would the best way to go about this problem be?

Answer Source

You can use the key argument to the min() function to find the tuple with the smallest second value:

>>> l = [(0, 0.0083553666846612491), (1, 0.0054999681509501821)]
>>> smallest = min(l, key=lambda x: x[1])[0]
>>> smallest

Here a lambda expression is used to select the second item of each tuple and min uses that value in its comparisons. min() returns the full tuple, so you can extract the first item using [0].

You can also use operator.itemgetter:

>>> from operator import itemgetter
>>> smallest = min(l, key=itemgetter(1))[0]
>>> smallest
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download