[英]Counting frequencies in a dictionary of lists
I have a dictionary with a bunch of lists, ie:我有一本带有一堆列表的字典,即:
{"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], etc...}
How can I count the frequencies of the numbers in each list?如何计算每个列表中数字的频率? and output a dictionary in the format:
和 output 格式的字典:
{"0": {"0": 4, "1": 2}, "1": {"0": 12, "1": 4}, etc..}
use collections.Counter
:使用
collections.Counter
:
from collections import Counter
spam = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}
eggs = {key:Counter(value) for key, value in spam.items()}
print(eggs)
output: output:
{'0': Counter({0: 4, 1: 2}), '1': Counter({0: 12, 1: 4})}
of course you can convert Counter
to dict
if you prefer当然,如果您愿意,您可以将
Counter
转换为dict
You can always make a counter yourself, that just counts for every element in the list how many appearances it has (notice that you can use an integer as a dictionary key and not just a string).您始终可以自己制作一个计数器,它只计算列表中每个元素的出现次数(请注意,您可以使用 integer 作为字典键,而不仅仅是字符串)。 Like this:
像这样:
a = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}
different_a = dict()
for key in a.keys():
counting_dict = dict()
for e in a[key]:
if str(e) in counting_dict:
counting_dict[str(e)] += 1
else:
counting_dict[str(e)] = 1
different_a[key] = counting_dict
But let's look at an nicer way than just counting the number of elements.但是让我们看一个比仅仅计算元素数量更好的方法。
My favorite is to use collections.Counter:我最喜欢的是使用 collections.Counter:
from collections import Counter
new_a = {key: Counter(value) for key, value in a.items()}
It turns the list into a set (a sort of list where each element can only appear once and the order of elements has no meaning), with the added feature that it counts the number of appearances.它将列表变成一个集合(一种列表,其中每个元素只能出现一次,元素的顺序没有意义),并增加了计算出现次数的功能。 Read more about this data structure here .
在此处阅读有关此数据结构的更多信息。
Try this (d is your dict):试试这个(d是你的字典):
d={"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}
res={i:{'0':k.count(0), '1':k.count(1)} for i,k in d.items()}
>>>print(res)
{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}
You can do this你可以这样做
d = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],}
a = dict()
for k,v in d.items():
count = dict()
for x in set(v):
count[str(x)] = v.count(x)
a[k] = count
print(a)
Output: Output:
{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}
Or You can do it using Dictionary Comprehension:或者您可以使用字典理解来做到这一点:
d = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],}
a = {k:{str(x):v.count(x) for x in set(v)} for k,v in d.items()}
print(a)
Output: Output:
{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.