def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v=list(d.values())
k=list(d.keys())
return k[v.index(max(v))]
为了给你一个想法,这里有一些候选方法:
def f1():
v=list(d1.values())
k=list(d1.keys())
return k[v.index(max(v))]
def f2():
d3={v:k for k,v in d1.items()}
return d3[max(d3)]
def f3():
return list(filter(lambda t: t[1]==max(d1.values()), d1.items()))[0][0]
def f3b():
# same as f3 but remove the call to max from the lambda
m=max(d1.values())
return list(filter(lambda t: t[1]==m, d1.items()))[0][0]
def f4():
return [k for k,v in d1.items() if v==max(d1.values())][0]
def f4b():
# same as f4 but remove the max from the comprehension
m=max(d1.values())
return [k for k,v in d1.items() if v==m][0]
def f5():
return max(d1.items(), key=operator.itemgetter(1))[0]
def f6():
return max(d1,key=d1.get)
def f7():
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v=list(d1.values())
return list(d1.keys())[v.index(max(v))]
def f8():
return max(d1, key=lambda k: d1[k])
tl=[f1,f2, f3b, f4b, f5, f6, f7, f8, f4,f3]
cmpthese.cmpthese(tl,c=100)
您可以使用
operator.itemgetter
来实现:而不是在内存中建立一个新的列表,使用
stats.iteritems()
。max()
函数的key
参数是一个计算用于确定如何排列项的键的函数。请注意,如果要使用另一个键值对“d”:3000,则此方法将只返回one或two中的one,即使它们都具有最大值。
如果使用Python3:
我已经测试了许多变体,这是用最大值返回dict键的最快方法:
为了给你一个想法,这里有一些候选方法:
测试字典:
以及Python 3.2下的测试结果:
在Python2.7下:
您可以看到,在Python 3.2和2.7下,
f1
是最快的(或者更完整地说,在本文的顶部,keywithmaxval
)相关问题 更多 >
编程相关推荐