[英]Passing Incomplete Parameter List in Python
I'm trying to use a reduce in Python, but I've found the function I need to call takes 2 parameters. 我正在尝试在Python中使用reduce,但是我发现需要调用的函数需要2个参数。
Is there a way for me to pass one of the parameters in, but not pass the first one? 有没有办法让我传递一个参数,但不传递第一个参数?
Like so 像这样
b = 10
reduce(foo, range(20), 0)
def foo(a, b):
return a + b
In your case you don't need to explicitly pass zero: 在您的情况下,您无需显式传递零:
print reduce(foo, range(20))
output: 输出:
190
Another interpretation of your question is, for the method foo(a, b)
you want a
to always be 10. 问题的另一种解释是,对于方法foo(a, b)
您希望a
始终为10。
If that is the case, you're not looking for reduce
- you're looking for map
. 如果是这种情况,则说明您不是在寻找reduce
,而是在寻找map
。 And you can achieve the "setting one of the parameters as 'fixed'" behavior by wrapping your foo
method 您可以通过包装foo
方法来实现“将参数之一设置为'fixed'”行为
def wrapper(f, a):
def x(b):
return f(a, b)
return x
def foo(a, b):
return a+b
print map(wrapper(foo, 10), range(11))
output: 输出:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.