Search code examples
pythonlistfrequency

Counter when 2 values are most frequent


For example, I got a list of lists with two values which are tied in being the most frequent. Lines = the list of lists, I used:

from collections import Counter
most_freq = Counter(bin for sublist in lines for bin in sublist).most_common(1)[0][0]

Iterating over the list, it prints only one result (I understand that's because of the 1).. I found recently in the forum the following code:

counts = collections.Counter(lines)
mostCommon = counts.most_common()
print(mostCommon)

But the error is "TypeError: unhashable type: 'list'" What should I change to print all most frequent values available?


Solution

  • This prints a list of the two most common items in the sublists:

    from collections import Counter
    most_common = Counter(item for sublist in lines for item in sublist).most_common(2)
    print([item for item, _ in most_common])
    

    After your comment, I think you are looking for the multimode:

    from statistics import multimode
    print(multimode(item for sublist in lines for item in sublist))