Python3 不能直接导入reduce

python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

reduce的用法

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

 

意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

?
1
2
3
4
5
6
7
from functools import reduce 
reduce ( lambda x,y: x + y, [ 1 , 2 , 3 ]) 
输出 6 
reduce ( lambda x, y: x + y, [ 1 , 2 , 3 ], 9
输出 15 
reduce ( lambda x,y: x + y, [ 1 , 2 , 3 ], 7
输出 13 

  

*functool标准库还有很多功能,可以参考网上的资料


转自:http://www.cnblogs.com/alan-babyblog/p/5194399.html

### 回答1: 在 Python 3 中,reduce 函数被移动到 functools 模块中,因此您需要从该模块导入 reduce 函数。请尝试以下代码: ``` from functools import reduce # 然后您可以使用 reduce 函数,例如: my_list = [1, 2, 3, 4, 5] product = reduce((lambda x, y: x * y), my_list) print(product) ``` 这将输出 `120`,即 `1*2*3*4*5` 的结果。 ### 回答2: 在Python3中,"reduce"函数不再是内建函数,而是被移除到"functools"模块中。所以当我们尝试使用"reduce"函数时会出现"NameError: name 'reduce' is not defined"的错误提示。 要解决这个问题,我们需要先导入"functools"模块,并使用其提供的"reduce"函数。具体步骤如下: 1. 在代码的开头添加以下导入语句: ```python from functools import reduce ``` 2. 接下来就可以正常使用"reduce"函数了。例如,我们可以使用Reduce函数计算一个列表中所有元素的和: ```python numbers = [1, 2, 3, 4, 5] sum = reduce(lambda x, y: x + y, numbers) print(sum) ``` 这样就能够正常运行使用"reduce"函数的代码了。注意,由于"reduce"函数已移除到"functools"模块中,所以必须先导入该模块才能使用"reduce"函数。 ### 回答3: Python3中,reduce函数已经从全局命名空间中移除,它现在被放置在functools模块中。要使用reduce函数,需要先导入functools模块。可以按照以下步骤解决问题: 1. 首先,在代码的开头部分导入functools模块。可以使用以下语句:`import functools`。 2. 然后,使用`functools.reduce()`来调用reduce函数。例如,如果你想使用reduce函数对一个列表进行求和,可以使用如下代码:`functools.reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])`。 以上就是解决问题的方法。通过导入functools模块并使用`functools.reduce()`调用reduce函数,就可以在Python3中使用reduce函数了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值