python - 如何将项目映射到python中的池映射结果
问题描述
from multiprocessing import Pool
def add (x):
return x + 2
if __name__ == '__main__':
x = [('a', 1) ,('b', 2) ,('c', 3), ('d', 4)]
y = list ()
for items, values in x:
y.append(values)
p = Pool(5)
response = p.map(add, y)
print(response)
p.close()
在上述情况下,我想将结果 [3, 4, 5, 6] 映射到 ['a', 'b','c','d'] 它应该是 [('a', 3) ,(' b', 3) ,('c', 5), ('d', 6)]
注意:我不能修改添加功能
解决方案
正如@alkasm 提到的,您可以使用列表理解并将zip
输入列表链接到结果列表。您还可以使用列表推导来创建y
列表。
试试这个代码:
from multiprocessing import Pool
def add (x):
return x + 2
if __name__ == '__main__':
x = [('a', 1) ,('b', 2) ,('c', 3), ('d', 4)]
y = [e[1] for e in x] # 1,2,3,4
p = Pool(5)
response = p.map(add, y)
res = list(zip([e[0] for e in x], response))
print(res)
p.close()
输出
[('a', 3), ('b', 4), ('c', 5), ('d', 6)]
推荐阅读
- python - 如何为 Python Swigged C++ 对象创建和分配回调函数
- python - Django DRF - 通过权限限制对列表视图的访问
- redux - 如何为 reduxForm() 设置全局默认值
- node.js - 在 node/express.js 子应用之间共享视图和静态文件
- sql - 将 SQL Developer 连接到 Redshift
- java - JSF f:convertNumber 在面板中有效,但在对话框中无效
- sass - 如何通过 SASS 更改 Bootstrap 4 的边框底部宽度?
- javascript - 在 React Native 项目中,为什么在导入中将顶级目录称为“app”?
- git - 为什么詹金斯从下载的 git repo 中删除空目录?
- c# - 当多个客户端连接时,我的多线程在线服务器变得太慢,C#