python - 计算 Python 字典列表中具有相同键的元素的数量
问题描述
我有以下 python 字典列表
list_of_dict = [
{'id': 0, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 0},
{'id': 1, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 4095},
{'id': 2, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 8092},
{'id': 0, 'au_type': 3, 'sequence_id': 0, 'AU_start_position': 5678},
{'id': 0, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 13525},
{'id': 1, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 13587},
{'id': 2, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 14576},
{'id': 0, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 15019},
{'id': 1, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 15560},
{'id': 2, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 16004}
]
我有seq_count
作为不同的总数'sequence_id'
和num_classes
作为不同的总数'au_type'
。在上面的例子中:
seq_count = 2
num_classes = 2
我需要实现一个列表numid_seq_cl[seq_count][num_classes]
,返回'id'
具有相同'au_type'
和的不同数量'sequence_id'
。在上面的例子中,
numid_seq_cl[0][1] = 3
numid_seq_cl[0][3] = 1
numid_seq_cl[1][1] = 3
numid_seq_cl[1][3] = 3
解决方案
在您的情况下,一个有意义的结果将是一个字典。对灵活对象
使用以下方法:collections.defaultdict
from collections import defaultdict
list_of_dicts = [
{'id': 0, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 0},
{'id': 1, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 4095},
{'id': 2, 'au_type': 1, 'sequence_id': 0, 'AU_start_position': 8092},
{'id': 0, 'au_type': 3, 'sequence_id': 0, 'AU_start_position': 5678},
{'id': 0, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 13525},
{'id': 1, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 13587},
{'id': 2, 'au_type': 1, 'sequence_id': 1, 'AU_start_position': 14576},
{'id': 0, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 15019},
{'id': 1, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 15560},
{'id': 2, 'au_type': 3, 'sequence_id': 1, 'AU_start_position': 16004}
]
numid_seq_cl = defaultdict(lambda : defaultdict(int)) # default structure
for d in list_of_dicts:
numid_seq_cl[d['sequence_id']][d['au_type']] += 1
numid_seq_cl = {k: dict(v) for k, v in numid_seq_cl.items()}
print(numid_seq_cl) # {0: {1: 3, 3: 1}, 1: {1: 3, 3: 3}}
这是您预期的索引:
print(numid_seq_cl[0][1]) # 3
print(numid_seq_cl[0][3]) # 1
print(numid_seq_cl[1][1]) # 3
print(numid_seq_cl[1][3]) # 3
推荐阅读
- ios - React-native 中的自定义按钮设计“使用 Apple 登录”
- python - Python - 左序二进制矩阵
- javascript - 通过锚标签或 window.open 打开 chrome 扩展
- clip-path - 对背景 img 使用剪辑路径,但对带有 img 的 div 不使用
- excel - 合并工作表,但在已合并数据的末尾添加新插入的行
- python - 存储在变量中的值不会从一个函数传递到另一个函数
- ffmpeg - 使用 FFMPEG 连接 YUV 以生成输出 YUV
- python - 如何从数据框设置消息
- spring-boot - 如何让 Spring 将骆驼箱转换为蛇箱?
- mysql - 撤销对 information_schema 的权限