5
\$\begingroup\$

I have a list of objects and I would like to see which ones are the most common. It is easy to find the or a most common object using python's Counter, but I haven't found a simple way to find all of the most common objects. The code below is working but I would guess there's a better way to do this.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
ranked_counts = counts.most_common().copy()
first_common_obj = ranked_counts.pop(0)
equally_common_objs = [first_common_obj[0]]
while ranked_counts:
    next_obj = ranked_counts.pop(0)
    if first_common_obj[1] == next_obj[1]:
        equally_common_objs.append(next_obj[0])
    else:
        break

print(equally_common_objs)
\$\endgroup\$
8
\$\begingroup\$

It would be easier, and have better performance, to iterate over Counter.most_common() rather than using .pop(0) lots.

From here you just want to use next until the value is not the same. Which is effectively what you're doing with .pop.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
items = iter(counts.most_common())
value, amount = next(items)
values = [value]
while True:
    value, a = next(items)
    if amount != a:
        break
    values.append(value)

print(values)

This is effectively grouping consecutive values together, and so you can instead use itertools.groupby rather than roll your own.

from collections import Counter
from itertools import groupby

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

_, values = next(groupby(Counter(input_lst).most_common(), lambda i: i[1]))
values = [value for value, _ in values]
print(values)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The first solution hit a StopIteration and then crashed, but the second solution worked for me (Python 3.7.6). \$\endgroup\$ – jss367 May 6 at 19:54
  • \$\begingroup\$ @jss367 That issue is present in your original code. \$\endgroup\$ – Peilonrayz May 6 at 19:54
  • \$\begingroup\$ @jss367 There is an additional issue that will cause a StopIteration error in both my solutions and an IndexError in yours. Please properly test your code, before blaming me for causing errors in your code. \$\endgroup\$ – Peilonrayz May 6 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.