-2

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
Small_J
  • 43
  • 1
  • 7
  • 2
    Any attempts from your side? You should provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and describe, why your attempts failed. – Mr. T May 22 '18 at 08:39
  • 1
    Related: [Finding the single most common element in a list](https://stackoverflow.com/questions/1518522/find-the-most-common-element-in-a-list) – Aran-Fey May 22 '18 at 08:45
  • @Aran-Fey: I have read your post before but couldn't find the answer – Small_J May 22 '18 at 08:51
  • @Aran-Fey I deleted my answer, don't know what to say : | – akash karothiya May 22 '18 at 08:59

1 Answers1

4

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.

Counter

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)]

numpy.unique

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]))

Counter + groupby

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])
jpp
  • 159,742
  • 34
  • 281
  • 339