首页 > 代码库 > 20170430python中reduce函数

20170430python中reduce函数

今天在搜用Python求阶乘的时候, 搜出来的最简单的是用reduce这个built-in function, 但是我在用reduce的时候,

却报NameError: name ‘reduce‘ is not defined. 于是又搜了一下,发现在python 3.0.0.0以后, reduce已经不在

built-in function里了, 要用它就得from functools import red

def ride(x,y):
return x*y
print (reduce(ride,[2, 4, 5, 7, 12]))

NameError: name ‘reduce‘ is not defined

更改:利用reduce实现连乘

from functools import reduce
def ride(x,y):
return x*y
print (reduce(ride,[2, 4, 5, 7, 12]))

3360

20170430python中reduce函数