I have two lists of interger:
A = [1,2,3,5,2,3]
B = [1,2,3,5,2,3,5]
I want to use most_common to get the top same count like this: [(2, 2), (3, 2)] for the list A and [(2, 2), (3, 2), (5, 2)] for the list B. How can I do this?
I have two lists of interger:
A = [1,2,3,5,2,3]
B = [1,2,3,5,2,3,5]
I want to use most_common to get the top same count like this: [(2, 2), (3, 2)] for the list A and [(2, 2), (3, 2), (5, 2)] for the list B. How can I do this?
One inefficient way is to use collections.Counter followed by a dictionary comprehension. Remember that Counter returns a dictionary, which can be manipulated like any other.
from collections import Counter
A_c = Counter(A)
B_c = Counter(B)
max_val = max(A_c.values())
A_res = [(k, v) for k, v in A_c.items() if v == max_val]
# [(2, 2), (3, 2)]
max_val = max(B_c.values())
B_res = [(k, v) for k, v in B_c.items() if v == max_val]
# [(2, 2), (3, 2), (5, 2)]
A more efficient solution is available via 3rd party library numpy. Here you benefit from holding counts in contiguous memory blocks.
import numpy as np
def max_counter(lst):
values, counts = np.unique(lst, return_counts=True)
idx = np.where(counts == counts.max())[0]
return list(zip(values[idx], counts[idx]))
A third solution combines itertools.groupby with collections.Counter. You should test to see which method is suitable and efficient for your data.
from collections import Counter
from itertools import groupby
from operator import itemgetter
def max_counter_grp(lst):
grouper = groupby(Counter(lst).most_common(), key=itemgetter(1))
return max((list(j) for _, j in grouper), key=lambda x: x[0][1])