在列表列表中找到最常见的元素 [英] Find the most common element in list of lists

查看:57
本文介绍了在列表列表中找到最常见的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的清单

a=[ ['a','b','a','a'],
    ['c','c','c','d','d','d']]

我想找到最常见的元素.我已经尝试过

I wanna find most common elemments. I have tried this

from collections import Counter
words = ['hello', 'hell', 'owl', 'hello', 'world', 'war', 'hello', 
         'war','aa','aa','aa','aa']

counter_obj = Counter(words)

counter_obj.most_common() 

,但仅适用于简单列表.我的输出应该是这样

but it works just for simple list. my output should be like this

[('a', 3), ('c', 3), ('d', 3), ('b', 1)]

推荐答案

在列表的元素上应用 Counter().update()选项,根据@BlueSheepToken的建议

Apply Counter().update() option on the elements of your list, Based on suggestion from @BlueSheepToken

from collections import Counter

words = [['a','b','a','a'],['c','c','c','d','d','d']]
counter = Counter(words[0])
for i in words[1:]: 
    counter.update(i)

counter.most_common()

输出:

[('a', 3), ('c', 3), ('d', 3), ('b', 1)]

这篇关于在列表列表中找到最常见的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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