首页 > 解决方案 > 合并两个列表的 Pythonic 方法

问题描述

我想将值附加到现有字典。这是我的代码:

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'}]]

我不喜欢进行 deepcopy 和 append 的内部循环。什么是pythonic方式来做到这一点?

标签: python

解决方案


你可以做一个列表理解:

[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'}]]

推荐阅读