【发布时间】:2015-01-05 23:55:46
【问题描述】:
在collections.Counter 中,方法most_common(n) 仅返回列表中的n 个最频繁的项目。我确实需要,但我也需要包括相同的计数。
from collections import Counter
test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])
-->Counter({'A': 3, 'C': 2, 'B': 2, 'D': 2, 'E': 1, 'G': 1, 'F': 1, 'H': 1})
test.most_common(2)
-->[('A', 3), ('C', 2)
我需要[('A', 3), ('B', 2), ('C', 2), ('D', 2)]
因为在这种情况下,它们的计数与 n=2 相同。我的真实数据是关于 DNA 代码的,可能非常大。我需要它有点效率。
【问题讨论】:
标签: python collections python-collections