Python 计算列表中的事件数

Python 计算列表中的事件数,python,list,count,Python,List,Count,我有3个列表,每个列表中都有唯一的元素,我想计算每个元素出现的次数。这里的唯一性意味着列表中的所有元素都是唯一的,没有重复的元素 数据示例如下: list(c[0]): list(c[1]): list(c[1]): a a a b b b c c d 所以期望的输出应该是 a:3,b:3,c:2,d

我有3个列表,每个列表中都有唯一的元素,我想计算每个元素出现的次数。这里的唯一性意味着列表中的所有元素都是唯一的,没有重复的元素

数据示例如下:

list(c[0]):       list(c[1]):       list(c[1]):      
a                 a                 a
b                 b                 b
c                 c
d
所以期望的输出应该是

a:3,b:3,c:2,d:1

我知道
计数器可以应用于一个列表中,但如何跨列表计算?

展平列表,然后使用计数器:

假设lst是三个相关列表的列表:

flat = [i for sub in lst for i in sub]
Counter(flat)

将3个列表与
itertools.chain
合并,然后使用
collections.Counter
对项目进行计数

from collections import Counter
from itertools import chain
c = [['a', 'b', 'c', 'd'], ['a', 'b'], ['a']]
print(dict(Counter(chain(*c))))
这将产生:

{'a': 3, 'b': 2, 'c': 1, 'd': 1}

使用
chain.from\u iterable
将列表转换为平面列表,然后将其馈送到
计数器

from collections import Counter
from itertools import chain
c = [['a', 'b', 'c', 'd'], ['a', 'b'], ['a']]
Counter(chain.from_iterable(c))
# Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})

Counter(itertools.chain.from\u iterable(c))
解包3元素列表的开销不值得抱怨,但
chain.from\u iterable
是存在的。