15

我将如何使用集合库中的计数器将列表列表转换为每个单词总体出现次数的计数?

例如[['a','b','a','c'], ['a','b','c','d']] -> {a:2, b:2, c:2, d:1}

ab并且c出现在两个列表中,但d只出现在一个列表中。

4

3 回答 3

22

使用生成器表达式set

>>> from collections import Counter
>>> seq = [['a','b','a','c'], ['a','b','c','d']]
>>> Counter(x for xs in seq for x in set(xs))
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

回应评论,没有生成器表达式

>>> c = Counter()
>>> for xs in seq:
...     for x in set(xs):
...         c[x] += 1
...
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
于 2013-10-06T16:20:20.883 回答
2

以下代码片段带来了列表项的所有出现次数,希望这会有所帮助。

 from collections import Counter

_list = [['a', 'b', 'c', 'd', 'a'],['a', 'a', 'g', 'b', 'e', 'g'],['h', 'g', 't', 'y', 'u']]

words = Counter(c for clist in _list for c in clist)
print(words)
于 2020-06-18T12:27:17.067 回答
1
from itertools import chain
from collections import Counter

seq = [['a','b','a','c'], ['a','b','c','d']]
c = Counter(chain(*[x for x in seq]))

print(c)
Counter({'a': 3, 'b': 2, 'c': 2, 'd': 1})
于 2021-01-09T14:09:00.943 回答