2024-05-08 03:13:40 发布
网友
我有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可以应用于一个列表中,但是如何跨列表计算呢?你知道吗
Counter
将3个列表与itertools.chain合并,然后使用collections.Counter对项目进行计数。你知道吗
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
chain.from_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})
将3个列表与
itertools.chain
合并,然后使用collections.Counter
对项目进行计数。你知道吗这将输出:
展平列表,然后使用计数器:
假设lst是三个相关列表的列表:
使用
chain.from_iterable
将列表转换为平面列表,然后将其馈送到Counter
相关问题 更多 >
编程相关推荐