In collections.Counter
, the method most_common(n)
returns only the n most frequent items in a list. I need exactly that but I need to include the equal counts as well.
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)
I would need [('A', 3), ('B', 2), ('C', 2), ('D', 2)]
since they have the same count as n=2 for this case. My real data is on DNA code and could be quite large. I need it to be somewhat efficient.
For smaller sets, just write a simple generator:
For larger set, use ifilter (or just use
filter
on Python 3):Or, since
most_common
are already ordered, just use a for loop and break on the desired condition in a generator:You can do something like this: