减少功能不能处理空列表 [英] Reduce function doesn't handle an empty list

查看:55
本文介绍了减少功能不能处理空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前创建了一个递归函数来查找列表的乘积. 现在,我创建了相同的函数,但是使用了reduce函数和lamdba.

I previously created a recursive function to find the product of a list. Now I've created the same function, but using the reduce function and lamdba.

运行此代码时,我会得到正确的答案.

When I run this code, I get the correct answer.

items = [1, 2, 3, 4, 10]
print(reduce(lambda x, y: x*y, items))

但是,当我提供空白列表时,会出现错误-reduce() of empty sequence with no initial value.为什么会这样?

However, when I give an empty list, an error occurs - reduce() of empty sequence with no initial value. Why is this?

当我创建递归函数时,我创建了处理空列表的代码,reduce函数的问题仅仅是它不是专门为处理空列表而设计的吗?还是还有其他原因?

When I created my recursive function, I created code to handle an empty list, is the issue with the reduce function just that it just isn't designed to handle and empty list? or is there another reason?

我似乎无法找到任何问题或任何在线解释原因的信息,我只能找到带有针对特定人员问题的解决方案的问题,而没有任何解释.

I cannot seem to find a question or anything online explaining why, I can only find questions with solutions to that particular persons issue, no explanation.

推荐答案

文档中编写:

如果存在可选的初始化程序,则将其放在计算中可迭代项的前面,并在可迭代项为空时用作默认值.如果未提供初始值设定项,并且iterable仅包含一项,则返回第一项.

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.

因此,如果您希望代码使用空列表,则应使用初始化程序:

So if you want your code to work with an empty list, you should use an initializer:

>>> reduce(lambda x, y: x*y, [], 1)
1

这篇关于减少功能不能处理空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆