我之前创建了一个递归函数来查找列表的乘积。
现在我创建了相同的函数,但使用了 reduce
函数和 lamdba
。
当我运行这段代码时,我得到了正确的答案。
items = [1, 2, 3, 4, 10]
print(reduce(lambda x, y: x*y, items))
但是,当我给出一个空列表时,会发生错误 - reduce() of empty sequence with no initial value
。这是为什么?
当我创建递归函数时,我创建了处理空列表的代码,reduce 函数的问题是否只是因为它不是为处理空列表而设计的?还是有其他原因?
我似乎无法在网上找到问题或任何解释原因的内容,我只能找到针对特定人员问题的解决方案的问题,没有任何解释。
最佳答案
正如 documentation 中所写的那样:
If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.
所以如果你想让你的代码使用一个空列表,你应该使用一个初始化器:
>>> reduce(lambda x, y: x*y, [], 1)
1
关于python - Reduce 函数不处理空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33945882/