python - 合并两个列表的 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方式来做到这一点?
解决方案
你可以做一个列表理解:
[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'}]]
推荐阅读
- angularjs - 如何禁用 ag-grid 中的整个列
- wordpress - 如何在 IIS 上使用 Word Press 修复添加插件错误?
- android - CoordinatorLayout (Toolbar+NestedScrollView+BottomNavigationView) 问题
- java - textinputlayout 密码切换图标被阻止
- java - 在Java中的另一个模型类中注入MVC模型类
- javascript - 在javascript中使.value值为0而不是null
- swift - 如何将本地 HTML 加载到我的 WebView 中?
- java - 如何让我的 SWT 应用程序在 Java 32 位和 Java 64 位机器上运行
- jekyll - jekyll 类别多词输出没有空格
- javascript - scrollTop addclass 跳转