可能重复:
Sorting or Finding Max Value by the second element in a nested list. Python
我写了一个程序,它给了我一个元组列表。我需要使用第二个值中的最大数字来获取元组。
(840, 32), (841, 3), (842, 4), (843, 4), (844, 6), (845, 6), (846, 12), (847, 6), (848, 10), (849, 4), ..snip...
我需要回来(840,32)因为32是元组中最高的第二个数字。我怎样才能做到这一点?我尝试过各种各样的方法,但这里仍然存在完整的代码:
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())
答案 0 :(得分:25)
将max()
与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)
In [24]: import operator
In [25]: max(lis, key=operator.itemgetter(1))
Out[25]: (840, 32)