[英]Pythonic way to merge two lists
我想將值附加到現有字典中。 這是我的代碼:
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的方式做到這一點?
您可以進行列表理解:
[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'}]]
嵌套列表理解就足夠了; 給出顯示的示例,對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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.