Psy*_*ath 5 python sorting dictionary
我有以下字典:
'{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}'
Run Code Online (Sandbox Code Playgroud)
对于这个字典,我想写一个函数,它返回具有最高值的三个键值对(所以在这种情况下键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)
Run Code Online (Sandbox Code Playgroud)
这给了我一个我想要查找的最大值的列表.但是我怎么从这里开始呢?有没有办法在没有反向查找的情况下做到这一点(这对词典来说很慢,对吧?)我觉得我可以更有效地/ pythonic地完成这项任务.
您也可以使用collections.Counterwith 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)]
Run Code Online (Sandbox Code Playgroud)
heapq.nlargest您可以使用堆队列来避免完全排序:
from heapq import nlargest
from operator import itemgetter
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}
res = nlargest(3, dct.items(), key=itemgetter(1))
print(res)
# [(19, 244675), (20, 115878), (18, 111490)]
Run Code Online (Sandbox Code Playgroud)