Tag: the sum () function provided by Python can accept a list and sum please write a prod () function to accept a list and use the reduce () to calculate the product:
1 #Python提供的sum () function can accept a list and sum, write a prod () function, you can accept a list and use reduce () to calculate the product:
Code:
2 3 from Functools import reduce 4 Li = [1,2,3,4,5,7] 5 print (sum (LI)) 6 7 def prod (x, y): 8 return x * y 9 Ten R = Reduce (Prod,li) one print (R)
Operation Result:
[[email protected] practice]# python map_reduce_2.py 22840[[email protected] practice]#
Code Explanation:
2 3 from functools import reduce #导入reduce模块 4 li = [1,2,3,4,5,7] #创建一个列表用于计算 5 print (sum (LI)) #打印求和结果 6 7 def prod (x, y): #定义函数prod, pass in two parameters x,y 8 return x * y #返回xProduct of Y and 9 10 r = reduce (prod,li) #reduce Incoming functions prod and list li 11 print (R) # Print results
This article is from the "Learning Notes" blog, so be sure to keep this source http://netsyscode.blog.51cto.com/6965131/1751356
"Python" Programming Learning exercises-2