元组python中的最大第二个元素 [英] max second element in tuples python

查看:158
本文介绍了元组python中的最大第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
排序或查找最大值嵌套列表中第二个元素的值. Python

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...

我需要取回(840,32),因为32是元组中最高的第二个数字.我怎样才能做到这一点?我尝试了多种方法,但是请注意,这里是完整的代码:

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

推荐答案

使用> c0> 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)

operator.itemgetter :

In [24]: import operator 

In [25]: max(lis, key=operator.itemgetter(1))
Out[25]: (840, 32)

这篇关于元组python中的最大第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆