Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the maximum value in a list of tuples in Python [duplicate]

Possible Duplicate:
Sorting or Finding Max Value by the second element in a nested list. Python

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 Ys in this list, but also want to know the X that it is bound to.

How do I do this?

like image 745
Berk Özbalcı Avatar asked Oct 30 '12 18:10

Berk Özbalcı


People also ask

How do you find the maximum value in a list of tuples in Python?

To find maximum of items in a Tuple in Python, use max() builtin function. We can also provide a key function for max() to transform the items and then find the maximum of those values.

How do you find duplicates in tuple Python?

Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .

What is the difference between MIN () and MAX () of a tuple?

min(): gives the smallest element in the tuple as an output. Hence, the name is min(). For example, max(): gives the largest element in the tuple as an output.


2 Answers

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]  In [81]: from operator import itemgetter  In [82]: max(lis,key=itemgetter(1))[0]    #faster solution Out[82]: 361 

using 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:

In [30]: %timeit max(lis,key=itemgetter(1)) 1000 loops, best of 3: 232 us per loop  In [31]: %timeit max(lis,key=lambda item:item[1]) 1000 loops, best of 3: 556 us per loop 
like image 113
Ashwini Chaudhary Avatar answered Sep 24 '22 06:09

Ashwini Chaudhary


In addition to max, you can also sort:

>>> lis [(101, 153), (255, 827), (361, 961)] >>> sorted(lis,key=lambda x: x[1], reverse=True)[0] (361, 961) 
like image 23
Burhan Khalid Avatar answered Sep 21 '22 06:09

Burhan Khalid