1 #计算 a = [1,2,3,4,5,6,7,8,9] 的和 2 a = [1,2,3,4,5,6,7,8,9] 3 sum = 0 4 for i in a: 5 sum += i 6 print('累加和:',sum) 7 8 #使用reduce()实现累加和 9 from functools import reduce 10 def add(x,y): 11 return x + y 12 sum = reduce(add,a) 13 print('累加和:',sum) 14 15 #把序列[1,3,5,7,9]变成13579 16 #将列表中的每个元素乘10加上后一个元素 17 def fn(x,y): 18 return x*10 + y 19 a = reduce(fn,[1,3,5,7,9]) 20 print('reduce执行结果:',a)
1 累加和: 45 2 累加和: 45 3 reduce执行结果: 13579