Python实现:按首元素匹配列表生成指定结构字典的方案
问题需求
给定以下列表:
list_keys = ['a', 'b', 'c'] list_a = ['a', 'a1', 'a2'] list_c = ['c', 'c1', 'c2']
需要编写Python脚本实现:
- 以
list_keys的元素作为字典的键 - 将
list_a、list_c作为对应键的值,匹配规则为列表首元素与键相等 - 无匹配的键对应空列表
期望输出:
{'a' : ['a', 'a1', 'a2'], 'b' : [], 'c' : ['c', 'c1', 'c2']}
现有代码及错误输出
当前尝试的代码(希望避免合并列表cmb):
list_keys = ['a', 'b', 'c'] list_a = ['a', 'a1', 'a2'] list_c = ['c', 'c1', 'c2'] cmb = list_a, list_c d = {} for k,v in zip(list_keys, cmb): d[k] = v print(d)
错误输出:
{'a': ['a', 'a1', 'a2'], 'b': ['c', 'c1', 'c2']}
解决方案
方法1:初始化空字典后匹配赋值
先创建所有键对应空列表的字典,再遍历目标列表,根据首元素匹配键并赋值:
list_keys = ['a', 'b', 'c'] list_a = ['a', 'a1', 'a2'] list_c = ['c', 'c1', 'c2'] # 初始化所有键对应空列表 result = {key: [] for key in list_keys} # 匹配并赋值list_a if list_a[0] in result: result[list_a[0]] = list_a # 匹配并赋值list_c if list_c[0] in result: result[list_c[0]] = list_c print(result)
方法2:字典推导式直接生成
通过字典推导式,根据键与列表首元素的匹配关系直接生成目标字典:
list_keys = ['a', 'b', 'c'] list_a = ['a', 'a1', 'a2'] list_c = ['c', 'c1', 'c2'] result = { key: list_a if key == list_a[0] else list_c if key == list_c[0] else [] for key in list_keys } print(result)
两种方法均无需合并列表cmb,且能输出符合要求的结果。
内容的提问来源于stack exchange,提问作者Ave
相关产品推荐
相关产品推荐

