简体   繁体   English

Python:在列表字典中使用Counter

[英]Python: use of Counter in a dictionary of lists

Given a dictionary of lists like this: d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]} 给出这样的列表字典: d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}

I want to be able to count how many times each individual value appears in all lists. 我希望能够计算每个值在所有列表中出现的次数。 In the example given, the intended outcome would be: 在给出的示例中,预期结果将是:

occurrences={0.1:4, 0.2:1, 1.1:1, 1.2:1, 2.1:1, 2.2:1}

I was thinking of using Counter in a line like this: 我想在这样的行中使用Counter

occurrences = Counter([k[0] for k in d.values()])

but the output is Counter({0.1: 1, 1.1: 1, 2.1: 1}) , meaning that the previous line only counts the occurrences of the first element of each list. 但是输出是Counter({0.1: 1, 1.1: 1, 2.1: 1}) ,这意味着前一行只计算每个列表的第一个元素的出现次数。

How can I extend this count to all elements of all lists? 如何将此计数扩展到所有列表的所有元素?

Since you don't appear to care about the keys of the dict, you can just use a comprehension: 既然您似乎并不关心字典的键,您可以使用一种理解:

>>> Counter(v for sublist in d.values() for v in sublist)
Counter({0.1: 4, 0.2: 1, 1.1: 1, 1.2: 1, 2.1: 1, 2.2: 1})

You need to put all the value lists in one flat list and then count. 您需要将所有值列表放在一个平面列表中,然后计数。 You can pass the dictionary's list of values to itertools.chain.from_iterable to flatten them: 您可以将字典的值列表传递给itertools.chain.from_iterable展平它们:

from collections import Counter
from itertools import chain

d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}
c = Counter(chain.from_iterable(d.values()))
print(c)
# Counter({0.1: 4, 0.2: 1, 1.2: 1, 2.2: 1, 1.1: 1, 2.1: 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM