Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max second element in tuples python [duplicate]

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

I've written a program that gives me a list of tuples. I need to grab the tuple with with the max number in the second value.

    (840, 32), (841, 3), (842, 4), (843, 4), (844, 6), (845, 6), (846, 12), (847, 6), (848, 10), (849, 4), ..snip...

I need to get back (840,32) because 32 is the highest second number in the tuple. How can I achieve this? I've tried a variety of ways but keep getting stuck here is the complete code:

    D = {}
    def divisor(n):
        global D
        L = []
        for i in range(1,n+1):
        if n % i == 0:
            L.append(i)
            D[n] = len(L)

    for j in range(1001):
        divisor(j)


    print(D.items())
like image 356
Mike Hoy Avatar asked Oct 23 '12 21:10

Mike Hoy


People also ask

How do you sort a tuple based on a second element in Python?

In python, if you want to sort a list of tuples by the second element then we have the function called sort() and by using lambda function as a key function. A custom comparator is a key function in sort().

Can a tuple hold more than 2 elements?

A tuple is nothing more than a finite ordered list. The number of elements it can hold can be any non-negative integer.

What is the correct way to get maximum value from tuple in Python?

The max() method returns the elements from the tuple with maximum value.


1 Answers

Use max() with lambda:

In [22]: lis=[(840, 32), (841, 3), (842, 4), (843, 4), (844, 6), (845, 6), (846, 12), (847, 6), (848, 10), (849, 4)]

In [23]: max(lis, key=lambda x:x[1])
Out[23]: (840, 32)

or operator.itemgetter:

In [24]: import operator 

In [25]: max(lis, key=operator.itemgetter(1))
Out[25]: (840, 32)
like image 167
Ashwini Chaudhary Avatar answered Oct 24 '22 23:10

Ashwini Chaudhary