簡體   English   中英

在列表列表中查找最常見的元素

[英]Find the most common element in list of lists

這是我的清單

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

我想找到最常見的元素。 我已經試過了

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

但它僅適用於簡單列表。 我的輸出應該是這樣的

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

根據@BlueSheepToken的建議,在列表的元素上應用Counter().update()選項

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

itertools.chain.from_iterable

collections.Counter接受任何可迭代的可哈希元素。 因此,您可以通過itertools.chain鏈接列表列表。 此解決方案的好處是它適用於任意數量的子列表。

from collections import Counter
from itertools import chain

counter_obj = Counter(chain.from_iterable(a))

print(counter_obj.most_common())

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM