计算列表中出现的次数

2024-05-08 03:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3个列表,每个列表中都有唯一的元素,我想计算每个元素的出现次数。这里的Unique表示列表中的所有元素都是唯一的,没有重复的元素。你知道吗

数据示例:

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

我知道Counter可以应用于一个列表中,但是如何跨列表计算呢?你知道吗


Tags: 数据元素示例列表counter次数listunique
3条回答

将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}

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

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

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

使用chain.from_iterable将列表转换为平面列表,然后将其馈送到Counter

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})

相关问题 更多 >