初始化器
位于可迭代
之后。这会导致部分应用出现问题。考虑这些(琐碎的)例子:
In [1]: from functools import reduce, partial
In [2]: f = partial(reduce, lambda a,b: a+b, 100)
In [3]: f([1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-816cce84b257> in <module>()
----> 1 f([1,2,3])
TypeError: reduce() arg 2 must support iteration
In [4]: f = partial(reduce, lambda a,b: a+b, initializer=100)
In [5]: f([1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-816cce84b257> in <module>()
----> 1 f([1,2,3])
TypeError: reduce() takes no keyword arguments
有什么技巧可以解决这个问题吗?
最佳答案
只需更改参数的顺序:
>>> f = partial(lambda func, init, iterable: reduce(func, iterable, init),
lambda a,b: a+b, 100)
>>> f([1,2,3])
106
关于Python:我可以使用初始化器部分应用reduce吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724663/