带有默认参数的Python映射

时间:2013-11-08 14:25:03

标签: python

假设我有一些采用默认参数的函数:

def fn(foo=0,bar=1):
    return something

如何创建地图并以伪代码指定哪些默认参数:

map(fn,foo=[1,2,3])

或:

map(fn,bar=[5,6,7])

3 个答案:

答案 0 :(得分:5)

您可以使用lambda使用默认参数包装函数:

map(lambda x: fn(x, bar=[1, 2, 3]), range(5))

答案 1 :(得分:3)

为了正确起见,partial用法似乎应该是

>>> from functools import partial
>>> def fn(foo=0,bar=1):
...     print 'foo {}, bar {}'.format(foo, bar)
...
>>> foo = [1,2,3]
>>> bar = [4,5,6]
>>> map(fn, foo)
foo 1, bar 1
foo 2, bar 1
foo 3, bar 1
[None, None, None]
>>> map(partial(fn, 0), bar)
foo 0, bar 4
foo 0, bar 5
foo 0, bar 6
[None, None, None]

答案 2 :(得分:1)

最好使用列表理解我认为

[foo(bar=i) for i in [1,2,3]]

至于map我可以提出的唯一方法你是用预期的关键字参数调用你的函数的函数

专用功能

def wrapper(func, kw):
    def wrapped(a):
        return func(**{kw: a})
    return wrapped

map(wrapper(foo, 'bar'), [1, 2, 3]) # if keyword argument is the same far all calls

或lambda

map(lambda x: foo(bar=x), range(5)) # if keyword argument is the same far all calls  

map(lambda x: foo(**{y:x}), ['bar', 'foo', 'bar'], range(3)) # if keyword arguments are different all calls