-1

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

edmamerto
  • 7,605
  • 11
  • 42
  • 66
  • Are the equal elements always adjacent with each other? – Eugene Sh. May 12 '17 at 17:22
  • @EugeneSh. no i just did it that way so it would be easy to understand, but if a sort function helps makes this more efficient then we can do that – edmamerto May 12 '17 at 17:23
  • Try: [collections.Counter](https://docs.python.org/2/library/collections.html#collections.Counter) – Maurice Meyer May 12 '17 at 17:23
  • use a [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) – juanpa.arrivillaga May 12 '17 at 17:24
  • 4
    Possible duplicate of [How to get unique values with respective occurrence count from a list in Python?](http://stackoverflow.com/questions/2392929/how-to-get-unique-values-with-respective-occurrence-count-from-a-list-in-python) – FamousJameous May 12 '17 at 17:24

2 Answers2

1

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    @e_mam106 the collections module is part of the python standard library (since a very long time!). it hardly qualifyes as a 'library'. any (reasonably recent) python distribution will come with the collections module. – hiro protagonist May 12 '17 at 17:32
0

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']
JkShaw
  • 1,927
  • 2
  • 13
  • 14