python - Reduce 函数不处理空列表

标签 python list lambda reduce

我之前创建了一个递归函数来查找列表的乘积。 现在我创建了相同的函数,但使用了 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/

相关文章:

python - Numpy/Scipy 中的卷积计算

Python 理解调度程序

python - 给定位置看到的唯一单词的累计数量的有序计数

c++ - 在集合上使用 lambda 表达式和 find_if

c# - 使用 linq lambda 从具有多个链接表的数据集中填充 C# 类

python - 如何使用 OpenCV-Python 检测照片上的黑色形状轮廓

python - 如何在 Python 中使用 Selenium 进行参数化/数据驱动测试

python - 如何将字符串更改为浮点列表和n维列表的 'n'?

python - 用字符串填充空列表元素python

java - 在 Stream API 中使用 checked 装饰器函数是好的解决方案吗?