Given a list: a = ['ed', 'ed', 'ed', 'ash', 'ash, 'daph']
I want to iterate through the list and get the top 2 most used names. So I should expect a result of ['ed', 'ash']
[Update]
how to go about this without using a library
Given a list: a = ['ed', 'ed', 'ed', 'ash', 'ash, 'daph']
I want to iterate through the list and get the top 2 most used names. So I should expect a result of ['ed', 'ash']
[Update]
how to go about this without using a library
collections.Counter
has a most_common
method:
from collections import Counter
a = ['ed', 'ed', 'ed', 'ash', 'ash', 'daph']
res = [item[0] for item in Counter(a).most_common(2)]
print(res) # ['ed', 'ash']
with most_common(2)
i get the 2 most common elements (and their multiplicity); the list-comprehension then removes the multiplicity and just removes the item in your original list.
try:
>>> from collections import Counter
>>> c = Counter(a)
>>> c
Counter({'ed': 3, 'ash': 2, 'daph': 1})
# Sort items based on occurrence using most_common()
>>> c.most_common()
[('ed', 3), ('ash', 2), ('daph', 1)]
# Get top 2 using most_common(2)
>>> [item[0] for item in c.most_common(2)]
['ed', 'ash']
# Get top 2 using sorted
>>> sorted(c, key=c.get, reverse=True)[:2]
['ed', 'ash']