将元组嵌套列表转换为以完整元组为键的字典列表
将元组嵌套列表转换为字典列表
原始数据
my_nested_list_of_tuples = [ [('AU041133(+)', 'Qtrt1'), ('Ahr(+)', 'Mex3c'), ('Arid3a(+)', 'Hmgb1')], [('AU041133(+)', 'Topors'), ('Ahr(+)', 'Mex3c'), ('Arid3a(+)', 'Hmgb1')], [('AU041133(+)', 'Tm9sf3'), ('Ahr(+)', 'Mex3c'), ('Arid3a(+)', 'Hmgb1')], [('AU041133(+)', 'Gsn'), ('Ahr(+)', 'Ireb2'), ('Arid3a(+)', 'Hmgb1')], [('AU041133(+)', 'Tm9sf3'), ('Ahr(+)', 'Ilf3'), ('Arid3a(+)', 'Arid3a')] ]
预期输出
[ {('AU041133(+)', 'Qtrt1'): 0, ('Ahr(+)', 'Mex3c'): 0, ('Arid3a(+)', 'Hmgb1'): 0}, {('AU041133(+)', 'Topors'): 0, ('Ahr(+)', 'Mex3c'): 0, ('Arid3a(+)', 'Hmgb1'): 0}, {('AU041133(+)', 'Tm9sf3'): 0, ('Ahr(+)', 'Mex3c'): 0, ('Arid3a(+)', 'Hmgb1'): 0}, {('AU041133(+)', 'Gsn'): 0, ('Ahr(+)', 'Ireb2'): 0, ('Arid3a(+)', 'Hmgb1'): 0}, {('AU041133(+)', 'Tm9sf3'): 0, ('Ahr(+)', 'Ilf3'): 0, ('Arid3a(+)', 'Arid3a'): 0} ]
错误尝试分析
你之前的代码存在两个核心问题:
- 复用了同一个
defaultdict对象,每次循环都将这个对象添加到列表,导致最终列表里的所有元素都是同一个字典,包含了所有元组的键。 - 把值设为列表并执行
append(0),而非直接赋值为0,不符合预期格式。
from collections import defaultdict d = defaultdict(list) dk=[] # for populating with list of dicts for k in my_nested_list_of_tuples: for i,v in k: d[(i,v)].append(0) dk.append(d)
解决方案
方法1:列表推导式(简洁写法)
用嵌套的字典推导式直接生成目标列表:
result = [{t: 0 for t in sublist} for sublist in my_nested_list_of_tuples]
- 外层遍历
my_nested_list_of_tuples中的每个子列表 - 内层遍历子列表中的每个元组,将元组作为键,值设为
0,生成对应字典 - 所有字典最终组成结果列表
方法2:普通循环(清晰易懂)
如果觉得列表推导式不够直观,可使用普通循环实现:
result = [] for sublist in my_nested_list_of_tuples: current_dict = {} for tpl in sublist: current_dict[tpl] = 0 result.append(current_dict)
- 处理每个子列表时,新建一个空字典
current_dict - 将当前子列表中的每个元组作为键存入字典,值固定为
0 - 把独立的字典添加到结果列表,确保每个元素对应原数据中的一个子列表
内容的提问来源于stack exchange,提问作者Ammar Sabir Cheema
相关产品推荐
相关产品推荐

