Counter.most_common(n)如何覆盖任意排序

时间:2017-03-28 17:32:47

标签: python python-2.7 counter

我可以使用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

1 个答案:

答案 0 :(得分:3)

doc explicitly says Counter.most_common()'s (tie-breaker) order for when counts are equal is arbitrary

  • 更新:PM2Ring告诉我Counter继承了dict的排序。插入顺序仅在3.6+版本中发生,并且只能在3.7中得到保证。该文档可能会滞后。
  • 在cPython 3.6+中,它们回退到原始插入顺序(请参阅底部),但不要依赖于该实现,因为根据规范,这不是定义的行为。如您所说,最好完全按照自己的意愿进行操作。
  • 我在底部显示了如何如何像您演示的那样monkey-patch 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)]