max second element in tuples python [duplicate]

我的梦境 提交于 2019-12-23 21:00:35

问题


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())

回答1:


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)


来源:https://stackoverflow.com/questions/13039192/max-second-element-in-tuples-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!