python - 将计数器与列表列表一起使用

标签 python list python-2.7 counter

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

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

abc 出现在两个列表中,但 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 - 将计数器与列表列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19211018/

相关文章:

python - TensorFlow 问题 google colab ; tensorflow._api.v1.compat.v 2' has no attribute ' __internal__

python - 如何在python中重复列表中的数字?

python - 将列表拆分为子列表中的 n 个项目,并添加剩余部分

python - 在 HTML 中同时查找多个 "Text"选项

Python:在unittest框架的测试用例中将一次性初始化放在哪里?

python - 如何使用plotly和袖扣绘制多轴?

python - Python中的for循环与C++有何不同?

Python:pip 尝试安装到/bin 目录

java - 在 java 中按列标题对二维列表进行排序

python - Python中按字母计数