2016-10-19 10 views
3

2Dのpythonリストで要素の頻度を数える方法があるかどうかを知りたい。Python-2Dリストの要素頻度をカウントする

a = [ ['hello', 'friends', 'its', 'mrpycharm'], 
     ['mrpycharm', 'it', 'is'], 
     ['its', 'mrpycharm'] ] 

iは、この2次元リスト内の各単語の頻度を見つけることができます:私はリストを持っている場合 1Dのリストについては、我々は

list.count(word) 

が、何を使用することができますか?

from collections import defaultdict 
d = defaultdict(int) 
for sublist in a: 
    for word in sublist: 
     d[word] += 1 

答えて

5

。それぞれsublistsumの単語数を取得するだけです。たとえば:

>>> my_word = 'its' 
>>> sum(sublist.count(my_word) for sublist in a) 
2 

あなたlist内の各単語の頻度が存在したい場合には、そのためにここに利用できる多くの良い答えがあります。また、あなたは(通常のdictを使用して)任意のimportなしでそれをしたい場合には、あなたが行うことがあります。

my_dict = {} 
for sublist in a: 
    for item in sublist: 
     if item not in my_dict: 
      my_dict[item] = 0 
     my_dict[item] += 1 

# Value of my_dict: 
{'friends': 1, 'is': 1, 'it': 1, 'its': 2, 'mrpycharm': 3, 'hello': 1} 
+0

代わりに、リスト内包のジェネレータ式を使用して高速化につながるかどうかは知っていますか? 'Counter(xはサブリストの中のxのサブリスト)' –

2

を想定し

+0

間違ったコレクション –

+1

@ juanpa.arrivillagaなぜそれは間違ったコレクションですか? – MrPyCharm

+0

sberryの答え –

1

あなたは既にについてlist.count()を知っている:あなたはdefaultdictを使用することができ、私はあなたが望むものを理解

>>> collections.Counter([x for sublist in a for x in sublist]) 
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1}) 

あるいは、

>>> c = collections.Counter() 
>>> for sublist in a: 
...  c.update(sublist) 
... 
>>> c 
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1}) 
関連する問題