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())
解决方案
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)
In [24]: import operator
In [25]: max(lis, key=operator.itemgetter(1))
Out[25]: (840, 32)