我有以下字典:
'{0: 0, 1: 11, 2: 26, 3: 43, 4: 14, 5: 29, 6: 34, 7: 49, 8: 49, 9: 108, 10: 124, 11: 108, 12: 361, 13: 290, 14: 2118, 15: 5408, 16: 43473, 17: 109462, 18: 111490, 19: 244675, 20: 115878, 21: 6960}'
对于这本字典,我想编写一个函数来返回具有最高值的三个键值对(因此在本例中为键 18、19、20)。
我想出了以下内容:
cachedict = nr_of_objects_per_century() #Dictionary mentioned above
def top_3_centuries():
max_nr_works_list = sorted(cachedict.values())
top_3_values = []
for i in range(len(max_nr_works_list)-3, len(max_nr_works_list)):
top_3_values.append(max_nr_works_list[i])
print(top_3_values)
这给了我要查找的最大值的列表。但是我该如何从这里开始呢?有没有一种方法可以在没有反向查找的情况下做到这一点(这对于字典来说很慢,对吧?)我觉得我可以更有效地/pythonic 地完成这项任务。
最佳答案
你也可以使用 collections.Counter
使用 most_common
(内部使用堆队列):
from collections import Counter
dct = {0: 0, 1: 11, 2: 26, 3: 43, 4: 14, 5: 29, 6: 34, 7: 49, 8: 49,
9: 108, 10: 124, 11: 108, 12: 361, 13: 290, 14: 2118, 15: 5408,
16: 43473, 17: 109462, 18: 111490, 19: 244675, 20: 115878, 21: 6960}
count = Counter(dct)
print(count.most_common(3)) # [(19, 244675), (20, 115878), (18, 111490)]
关于python - 返回字典中的三个最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53390526/