首页 > 解决方案 > 如何将项目映射到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)]

注意:我不能修改添加功能

标签: python

解决方案


正如@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)]

推荐阅读