2个值最频繁时计数 [英] Counter when 2 values are most frequent

查看:64
本文介绍了2个值最频繁时计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我得到一个包含两个值的列表列表,这两个值是最常见的.行数=我使用过的列表列表:

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]

遍历列表,它仅显示一个结果(我知道是因为1).我最近在论坛上发现以下代码:

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)

但是错误是"TypeError:无法散列的类型:'list'";我应该更改什么才能打印所有可用的最常用值?

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

推荐答案

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

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

这篇关于2个值最频繁时计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆