Reduce 函数不处理空列表
Reduce function doesn't handle an empty list
我之前创建了一个递归函数来查找列表的乘积。
现在我创建了相同的函数,但使用 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
reduce()
需要一个初始值来开始其操作。如果序列中没有值并且没有明确的值可以开始,那么它就不能开始操作并且不会有有效的 return 值。指定一个明确的初始值,以允许它对空序列进行操作:
print (reduce(lambda x, y: x*y, items, 1))
我之前创建了一个递归函数来查找列表的乘积。
现在我创建了相同的函数,但使用 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
reduce()
需要一个初始值来开始其操作。如果序列中没有值并且没有明确的值可以开始,那么它就不能开始操作并且不会有有效的 return 值。指定一个明确的初始值,以允许它对空序列进行操作:
print (reduce(lambda x, y: x*y, items, 1))