简体   繁体   English

合并两个列表的Python方式

[英]Pythonic way to merge two lists

I want to append value to an existing dictionary. 我想将值附加到现有字典中。 Here is my code: 这是我的代码:

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

I don't like the inner loop which does deepcopy and append. 我不喜欢进行深度复制和追加的内部循环。 What is a pythonic way to do that? 什么是Python的方式做到这一点?

You could do a list-comprehension: 您可以进行列表理解:

[tmp_result + list(x) for x in cross_configs]

Example : 范例

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

A nested list comprehension will suffice; 嵌套列表理解就足够了; the explicit call to dict is sufficient to avoid the need for deepcopy given the example shown. 给出显示的示例,对dict的显式调用就足以避免需要进行deepcopy

generated_configs = [[dict(y) for y in tmp_result + list(x)] for x in cross_configs]

If you object to tmp_result + list(x) , use itertools.chain instead. 如果您反对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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM