我想知道在2D python列表中是否有计算元素频率的方法。对于一维列表,我们可以使用
list.count(word)但如果我有一份清单:
a = [ ['hello', 'friends', 'its', 'mrpycharm'], 
      ['mrpycharm', 'it', 'is'], 
      ['its', 'mrpycharm'] ]我能找到这个2D列表中每个单词的频率吗?
发布于 2016-10-19 19:36:52
如果我明白你想要什么,
>>> 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})https://stackoverflow.com/questions/40140067
复制相似问题