简体   繁体   中英

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?

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.

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.

from itertools import chain
generated_configs = [[dict(y) for y in chain(tmp_result, x)] for x in cross_configs]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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