2D列表中的Python计数元素频率[重复]
发布于 2021-01-29 14:09:54
这个问题已经在这里有了答案 :
有效地计算python中的单词频率 (8个答案)
4年前关闭。
我想知道是否有一种方法可以计算2D python列表中的元素频率。对于一维列表,我们可以使用
list.count(word)
但是,如果我有一个清单:
a = [ ['hello', 'friends', 'its', 'mrpycharm'],
['mrpycharm', 'it', 'is'],
['its', 'mrpycharm'] ]
我可以在此2D列表中找到每个单词的频率吗?
关注者
0
被浏览
172
1 个回答
-
假设我了解你想要什么,
>>> 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})