首页 > 解决方案 > 计算 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

标签: python

解决方案


在您的情况下,一个有意义的结果将是一个字典。对灵活对象
使用以下方法: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

推荐阅读