我可以使用Counter.most_common()功能完成排名/排序,从而避免这一行:d = sorted(d.items(), key=lambda x: (-x[1],x[0]), reverse=False)
??
挑战: 给你一个字符串。字符串只包含小写的英文字母字符。你的任务是找到字符串中最常见的三个字符。
输出格式: 在单独的行上打印三个最常见的字符及其出现次数。按出现次数的降序对输出进行排序。如果出现次数相同,则按升序对字符进行排序。
在完成此操作时,我使用了dict,Counter和sort,以确保“出现次数相同,按升序对字符进行排序”。内置的Python sorted
功能确保按计数排序,然后按字母顺序排序。 我很好奇是否有办法覆盖Counter.most_common()
默认的任意排序/顺序逻辑,因为它在选择前3时似乎忽略了结果的词典顺序。
import sys
from collections import Counter
string = sys.stdin.readline().strip()
d = dict(Counter(string).most_common(3))
d = sorted(d.items(), key=lambda x: (-x[1],x[0]), reverse=False)
for letter, count in d[:3]:
print letter, count
答案 0 :(得分:3)
Counter.most_common
使用您自己的排序功能,但这是个皱眉。 (您编写的代码可能不小心依赖了它,因此在未打补丁时会中断。)Counter
子类化为MyCounter
,以便覆盖其most_common
。痛苦且不太方便。most_common()
中任意决胜局顺序的代码和测试most_common()
不应硬接线,我们应该能够将比较键或排序函数传递到__init__()
中。猴子修补Counter.most_common()
:
def patched_most_common(self):
return sorted(self.items(), key=lambda x: (-x[1],x[0]))
collections.Counter.most_common = patched_most_common
collections.Counter('ccbaab')
Counter({'a': 2, 'b': 2, 'c': 2})
证明在cPython 3.7中,任意顺序是插入顺序(每个字符的第一次插入):
Counter('abccba').most_common()
[('a', 2), ('b', 2), ('c', 2)]
Counter('ccbaab').most_common()
[('c', 2), ('b', 2), ('a', 2)]