遍历两个列表配对,缺失对应键时在正确位置插入None
问题解决:按配对位置匹配字典键并补全None
需求说明
给定映射字典stuff_types和两个等长列表a、b,需要按(a[i], b[i])的配对位置生成结果列表:
- 若配对中任意一个元素是
stuff_types的键,就将对应字典值加入结果 - 若配对中两个元素都不在字典键中,就在该位置插入
None
期望结果:
[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]
错误代码分析
之前的代码会遍历配对中的每个元素单独判断,导致结果长度是原配对数的2倍,不符合需求:
stuff_types = { "spana": {"type": "BOOK"}, "geom": {"type": "GLASS"}, "hlian": {"type": "POT"} } a = ['kal', 'khp', 'khp', 'khp', 'geom'] b = ['hlian', 'spana', 'piper', 'meli', 'phin'] the_list = [] for tup in zip(a, b): for x in tup: if x in stuff_types: the_list.append(stuff_types[x]) else: the_list.append(None) print(the_list)
正确实现代码
调整逻辑,对每个配对只做一次判断,优先检查第一个元素,再检查第二个:
stuff_types = { "spana": {"type": "BOOK"}, "geom": {"type": "GLASS"}, "hlian": {"type": "POT"} } a = ['kal', 'khp', 'khp', 'khp', 'geom'] b = ['hlian', 'spana', 'piper', 'meli', 'phin'] the_list = [] for x, y in zip(a, b): if x in stuff_types: the_list.append(stuff_types[x]) elif y in stuff_types: the_list.append(stuff_types[y]) else: the_list.append(None) print(the_list)
运行后输出符合期望的结果:
[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

