Python列表中的Python计数元素频率

Ahm*_*ani 3 python

我想知道是否有办法计算2D python列表中的元素频率.对于1D列表,我们可以使用

list.count(word)
Run Code Online (Sandbox Code Playgroud)

但如果我有一个清单怎么办:

a = [ ['hello', 'friends', 'its', 'mrpycharm'], 
      ['mrpycharm', 'it', 'is'], 
      ['its', 'mrpycharm'] ]
Run Code Online (Sandbox Code Playgroud)

我可以在这个2D列表中找到每个单词的频率吗?

sbe*_*rry 5

假设我理解你想要的东西,

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

要么,

>>> c = collections.Counter()
>>> for sublist in a:
...     c.update(sublist)
...
>>> c
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1})
Run Code Online (Sandbox Code Playgroud)