简体   繁体   English

Python:如何将映射函数的输出作为参数传递

[英]Python: How to pass output of the map function as arguments

I need to pass some arguments to the starmap_async function.我需要将一些参数传递给starmap_async函数。 I have a list my_list that has different values in it and some constants that are repeated.我有一个列表my_list ,其中包含不同的值和一些重复的常量。 I have a way to pass the arguments as bellow:我有一种方法可以将参数传递如下:

import multiprocessing as mp
from itertools import repeat

def f(a,b,c,d):
    return (a,b,c,d)

my_list = [1,2,3,4,5]

with mp.Pool(cpu_num) as pool:
    res = pool.starmap_async(f, zip(my_list, repeat(a),repeat(b),repeat(c),repeat(d)))
    pool.close()
    pool.join()
    res.get()

It works and generates arguments like this which is the desired output:它可以工作并生成这样的参数,这是所需的输出:

(1,a,b,c,d)
(2,a,b,c,d)
(3,a,b,c,d)
(4,a,b,c,d)
(5,a,b,c,d)

Now I want to use the map function to do something like this:现在我想使用map函数来做这样的事情:

res = pool.starmap_async(f, zip(my_list, repeat(list(map(repeat, 
[a, b, c, d])))))

but then I end up with arguments like this:但后来我得到了这样的论点:

(1,(a,b,c,d))
(2,(a,b,c,d))
(3,(a,b,c,d))
(4,(a,b,c,d))
(5,(a,b,c,d))

How can I fix that issue?我该如何解决这个问题?

Try this:尝试这个:

import multiprocessing as mp
from itertools import repeat

def f(a,b,c,d):
    return (a,b,c,d)

my_list = [1,2,3,4,5]

with mp.Pool(cpu_num) as pool:
    res = pool.starmap_async(f, zip(my_list, *map(repeat, (a,b,c,d))))
    pool.close()
    pool.join()
    res.get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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