我刚接触 Python3,现在陷入一个问题。
问题陈述:我有一个 defaultdict,它的一个键有多个值。在这些多个值中,有相似的值,也有不同的值。
现在,我想获取每个键的摘要(基于唯一记录的计数)。
字典(名为“d”)如下 defaultdict(, {'0': ['"126"},', '"115"},', '"60"},'], '1' : ['"126"},'], '2': ['"126"},', '"126"},', '"126"},', '"148"},', '"99"},'], '3': ['"126"},', '"226"},'], '4': ['"126"},', '"90"},'] , })
预期输出:
0: countALL :3; 1: countALL :1; 2: countALL :3; 3: countALL :2; 4: countALL :2;
例如,对于键“2”,有 3 条记录 126、1 条 148 和 1 条 99。因此摘要将为 3,因为存在三种类型的唯一记录。
这是用于我的研究的 Python3 程序,我用它来区分来自网络的不同类型的流量。
预期结果:
0: countALL :3; 1: countALL :1; 2: countALL :3; 3: countALL :2; 4: countALL :2;
最佳答案
这是我对您的问题的解释,尽管我的解释可能不正确。
from collections import Counter
data = {1: [2,3,4,3,4], 2: [6,5,3,5]}
for key, values in data.items():
print(f'{key} has the following unique counts {Counter(values)}')
输出以下内容:
1 has the following unique counts Counter({3: 2, 4: 2, 2: 1})
2 has the following unique counts Counter({5: 2, 6: 1, 3: 1})
关于python - 如何计算python3中defaultdict的唯一记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556918/