我想将值附加到现有字典中。这是我的代码:
tmp_result = [{'M': 8}, {'N': 16},]
cross_configs = [({'device': 'cpu'},), ({'device': 'cuda'},)]
import copy
generated_configs = []
for config in cross_configs:
for value in config:
new_value = copy.deepcopy(tmp_result)
new_value.append(value)
generated_configs.append(new_value)
print (generated_configs)
Output:
[[{'M': 8}, {'N': 16}, {'device': 'cpu'}], [{'M': 8}, {'N': 16}, {'device': 'cuda'}]]
我不喜欢进行深度复制和附加的内部循环。什么是Python的方式做到这一点?
答案 0 :(得分:1)
您可以进行列表理解:
[tmp_result + list(x) for x in cross_configs]
示例:
tmp_result = [{'M': 8}, {'N': 16},]
cross_configs = [({'device': 'cpu'},), ({'device': 'cuda'},)]
print([tmp_result + list(x) for x in cross_configs])
# [[{'M': 8}, {'N': 16}, {'device': 'cpu'}], [{'M': 8}, {'N': 16}, {'device': 'cuda'}]]
答案 1 :(得分:0)
嵌套列表理解就足够了;在给出的示例中,对dict
的显式调用足以避免需要deepcopy
。
generated_configs = [[dict(y) for y in tmp_result + list(x)] for x in cross_configs]
如果您反对tmp_result + list(x)
,请改用itertools.chain
。
from itertools import chain
generated_configs = [[dict(y) for y in chain(tmp_result, x)] for x in cross_configs]