简体   繁体   中英

Selecting smallest value from a list of coordinate tuples

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?

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
1

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
1

This should work:

min_tuple = min(your_list, key=lambda item: item[1])

So we are providing the method for tuple comparition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM