我有一段旧版 python2 代码,如下所示
# dict1 and dict2 are inputs. dict2 is where the value is a 4-tuple
return {
key: [
NamedTuple1(val1, val2, val3, val4),
NamedTuple2(
dict2.get(key, (None, None, None, None))[0],
dict2.get(key, (None, None, None, None))[1],
dict2.get(key, (None, None, None, None))[2],
dict2.get(key, (None, None, None, None))[3],
),
]
for key, (val1, val2, val3, val4) in dict1.items()
}
我不喜欢这段代码,因为它每次迭代都会
dict2.get(key, (None, None, None, None))
4x,而且我觉得应该有一种更简单的方法来编写它。有没有办法将 dict2
放入 for 循环中,对于缺少 key
,只需返回一个 (None, None, None, None)
,然后在 NamedTuple2
中展开它?
我认为您应该能够在这个特定示例中使用参数解包。唯一的假设是
dict2
中的每个值都需要有 4 个项目长。
# dict1 and dict2 are inputs. dict2 is where the value is a 4-tuple
return {
key: [
NamedTuple1(val1, val2, val3, val4),
NamedTuple2(*dict2.get(key, (None, None, None, None))),
]
for key, (val1, val2, val3, val4) in dict1.items()
}