简体   繁体   English

python字典中每个键的多个变量计数频率

[英]Counting frequency of multiple variables for each key in python dictionary

I managed to merge two lists (one representing the key, the other one the values) in a dictionary, in order to further count the frequency of the values. 我设法在字典中合并了两个列表(一个代表键,另一个代表值),以便进一步计算值的频率。 That gives me aa dictionary with multiples values in a list for each key : 这给了我一个字典,其中每个键的列表中都有多个值: 在此处输入图片说明

I now want to count, for each key, the total number of DIFFERENT VALUES, for eg on my printscreen, for the key 1068, there are 2 different keys (70803, 70805). 现在,我想为每个键计算不同值的总数,例如在我的打印屏幕上,对于键1068,有2个不同的键(70803、70805)。 I tried this: 我尝试了这个: 在此处输入图片说明

However, it only gives me the TOTAL times the values appears,which is not what I want. 但是,它只给我显示值的TOTAL倍,这不是我想要的。 As I am a very beginer in that, I have no idea how to proceed (especially with that dictionary with lists inside) 因为我是一个初学者,所以我不知道如何进行操作(尤其是其中带有列表的字典)

Thanks to all! 谢谢大家!

Loïc 洛伊奇

If I understand your question correctly, the following should do the trick: 如果我正确理解了您的问题,则应采取以下措施:

for k, v in d.items():
    print(k, len(set(v)))

For each list of values you create a set of the elements and get its length. 对于每个值列表,您创建一组元素并获取其长度。

here is my code: first, the dictionnary I obtain from the two lists: 这是我的代码:首先,我从两个列表中获得字典:

from collections import defaultdict
keys = ['31', '53', '57', '57', '57', '82', '82', '82', '82', '82', '82',         '82', '82', '82','82']
values = ['70803', '70901', '70801', '70801', '70801', '70801', '70804',  '70812', '70812', '70812', '70812', '70813', '70813', '70813', '70813']

d = {}
for k,v in zip(keys, values):
 d.setdefault(k, []).append(v)
d

which return me: 返回我:

 {'31': ['70803'],
'53': ['70901'],
'57': ['70801', '70801', '70801'],
'82': ['70801',
'70804',
'70812',
'70812',
'70812',
'70812',
'70813',
'70813',
'70813',
'70813']}

I then want to count for each key, the number of different values it has. 然后,我想为每个键计数它具有的不同值的数量。 When I try to proceed: 当我尝试继续时:

from collections import Counter
from collections import defaultdict
d = {'31': ['70803'],
'53': ['70901'],
'57': ['70801', '70801', '70801'],
'82': ['70801',
'70804',
'70812',
'70812',
'70812',
'70812',
'70813',
'70813',
'70813',
'70813']}
for k, v in d.items():
   print(k, len(set(v))

It returns me: 它返回我:

File "<ipython-input-5-f243768fffa2>", line 248
print(k, len(set(v))
                    ^

SyntaxError: unexpected EOF while parsing SyntaxError:解析时出现意外的EOF

So here I am :) I don't know how to proceed further 所以我在这里:)我不知道该怎么做

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

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