向map函数传递可变数量的参数

2024-04-26 13:43:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个函数,它的原型是:

def my_func(fixed_param, *args)

我希望使用多个参数运行此函数(不必每次运行的参数数相同),例如:

^{pr2}$

其中[1,2,3]和[1,2,3,4]分别对应于arg的第一组和第二组参数。在

但这行代码失败,并出现以下错误:

TypeError: my_func() got multiple values for keyword argument 'fixed_param'

Tags: 函数代码参数parammydef错误arg
3条回答

我不太确定mapvs list comprehension的性能,因为通常这是您使用的函数的问题。不管怎样,你的选择是:

map(lambda x: my_func(3, *x), ...)

或者

^{pr2}$

itertools中的所有函数一样,starmap返回一个迭代器,因此如果需要列表,则必须将其传递给list构造函数。这肯定比listcomp慢。在

编辑基准:

In [1]: def my_func(x, *args):
   ...:     return (x, ) + args
   ...: 

In [2]: from functools import partial

In [3]: from itertools import starmap

In [4]: import random

In [5]: samples = [range(random.choice(range(10))) for _ in range(100)]

In [6]: %timeit map(lambda x: my_func(3, *x), samples)
10000 loops, best of 3: 39.2 µs per loop

In [7]: %timeit list(starmap(partial(my_func, 3), samples))
10000 loops, best of 3: 33.2 µs per loop

In [8]: %timeit [my_func(3, *s) for s in samples]
10000 loops, best of 3: 32.8 µs per loop

为了比较起见,让我们稍微改变一下函数

In [9]: def my_func(x, args):
       ...:     return (x, )  + tuple(args)
       ...: 

In [10]: %timeit [my_func(3, s) for s in samples]
10000 loops, best of 3: 37.6 µs per loop

In [11]: %timeit map(partial(my_func, 3), samples)
10000 loops, best of 3: 42.1 µs per loop

同样,列表理解更快。在

我认为您的代码只需做一些小的更改即可工作:

def f(l, all_args):
    print "Variable", all_args
    print "Fixed", l

map(partial(f, 1), [[1, 2, 3], [1, 2, 3, 4]])

>>> Variable [1, 2, 3]
>>> Fixed 1
>>> Variable [1, 2, 3, 4]
>>> Fixed 1

如果使用列表理解,则可以解压缩参数列表:

res= [my_func(3, *args) for args in [[1, 2, 3], [1, 2, 3, 4]]]

但是你不能用map来做这个。如果坚持使用map,则需要一个helper函数:

^{pr2}$

相关问题 更多 >