我如何使用集合库中的计数器将列表列表转换为每个单词整体出现次数的计数?
例如. [[‘a’,’b’,’a’,’c’],[‘a’,’b’,’c’,’d’]] – > {a:2,b:2,c:2,d:1}
即a,b和c出现在两个列表中,但d仅出现在一个列表中.
解决方法:
使用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})
标签:python,list,python-2-7,counter
来源: https://codeday.me/bug/20190723/1508430.html