Python map list item to function with arguments

前端 未结 4 2061
我寻月下人不归
我寻月下人不归 2020-12-04 16:40

Is there any way to map list items to a function along with arguments. I have a list:

pages = [p1, p2, p3, p4, p5...]

And I have to call fu

4条回答
  •  囚心锁ツ
    2020-12-04 16:57

    Note that if you're planning to use map for distributed computations (i.e. using multiprocessing) it will not unpack the arguments as one could expect. Say you want to distribute your call to myFunc (which accepts two arguments: page and additionalArgument) with:

    pages = [p1, p2, p3, p4, p5...]
    

    If you specify a list of args (tuples), i.e.

    args = [(page, additionalArgument) for page in pages]
    

    map will not unpack the args tuple and will pass only one argument (tuple) to myFunc:

    pool.map(myFunc, args)  # map does not unpack the tuple
    

    You will need to use multiprocessing.starmap instead

    starmap is like map() except that the elements of the iterable are expected to be iterables that are unpacked as arguments.

    i.e.

    pool.starmap(myFunc, args)  # tuples are unpacked and two arguments are passed to myFunc
    

提交回复
热议问题