2个值最频繁时的计数器

Counter when 2 values are most frequent

例如,我得到了一个列表列表,其中有两个值是最常见的。 lines = 列表的列表,我用的是:

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

遍历列表,它只打印一个结果(我知道那是因为 1.. 我最近在论坛中发现了以下代码:

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

但错误是“TypeError: unhashable type: 'list'” 我应该更改什么以打印所有可用的最常用值?

您可以使用 count() method from the list, in order to find the total occurences of each sublist and then use the max 函数找到出现频率最高的一个:

most_common = max(lines, key=lambda e: lines.count(e))

这将打印子列表中两个最常见项目的列表:

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

根据您的评论,我认为您正在寻找多模:

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

可能添加:

most = Counter(b for sublist in lines for b in sublist).most_common(1)[0][0] # most freq'
all_freq = Counter(g for sublist in lines for g in sublist).most_common() 
# prints all frequencies
how_many_times_most_appears = Counter(b for sublist in lines for b in sublist).most_common(1)[0][1] # The most frequent
for k in all_freq:
    if k[1] == how_many_times_most_appears:
        print(k)
 
 # finding which value is same as the most