N个最大值的dict与重复

时间:2013-04-13 16:11:02

标签: python sorting dictionary

例如我们有这个词:

scores={'L Messi':18, 'R Falcao':16, 'R Van Persie':14, 'F Torres':0, 'C Ronaldo':16}

所以,我需要实现一个函数,它将打印前N个最佳分数(最大值)。对于此示例,如果 n = 3 ,则应打印此内容:

L Messi 18
C Ronaldo 16
R Falcao 16
R Van Persie 14

有任何建议怎么做?

2 个答案:

答案 0 :(得分:3)

使用collections.Counter及其.most_common()方法:

>>> from collections import Counter
>>> scores={'L Messi':18, 'R Falcao':16, 'R Van Persie':14, 'F Torres':0, 'C Ronaldo':16}
>>> scores = Counter(scores)
>>> for name, score in scores.most_common(4):
...     print '{}: {}'.format(name, score)
... 
L Messi: 18
R Falcao: 16
C Ronaldo: 16
R Van Persie: 14

如果您 要自己实施.most_common()代码,至少reference the .most_common() source使用heapq

要获得最常见的,您可以在此基础上构建:

def most_common_values(counter, count):
    values = set()
    most_common = iter(counter.most_common())
    while len(values) < count:
        key, value = next(most_common)
        values.add(value)
        yield key, value

对于你的例子:

>>> for name, score in most_common_values(scores, 3):
...     print '{}: {}'.format(name, score)
... 
L Messi: 18
R Falcao: 16
C Ronaldo: 16
R Van Persie: 14

答案 1 :(得分:0)

scores = {'L Messi':18, 'R Falcao':16, 'R Van Persie':14, 'F Torres':0, 'C Ronaldo':16}
top_scores = sorted(set(scores.values()), reverse=True)[:3]
filtered = sorted([[e, scores[e]] for e in scores if scores[e] in top_scores], key=lambda k: k[1], reverse=True)
for n, s in filtered:
    print("%s: %s" % (n, s))