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 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    假设我了解你想要什么,

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看