python - 如何计算python3中defaultdict的唯一记录

标签 python python-3.x

我刚接触 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/

相关文章:

python - 2048 场比赛 - AI 平均得分不能超过 256

python - 如何对不同大小的向量进行向量化运算

Python KeyError 和 ValueError 不一致?

python - StandardScaler "with_std=False or True"和 "with_mean=False or True"之间的区别

python - 欧式距离的高效计算

python - 从 csv 文件导入数据 - 为什么他们打印不同的东西?

python-3.x - 如何从 Adwords API 中提取数据并放入 Pandas 数据框

python - 运行 flake8 给出 - AttributeError : 'OptionManager' object has no attribute 'config_options'

python - 值错误: [E024] Could not find an optimal move to supervise the parser

python - 跨进程共享多处理同步原语