例如我们有这个字典:
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
有什么建议怎么做吗?
例如我们有这个字典:
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
有什么建议怎么做吗?
使用方法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()
代码,至少要引用.most_common()
源代码,它使用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
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))