lambda python
The reduce() function applies on each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.
reduce()函数适用于可迭代集合的每个元素,并返回简化后的值(基于通过函数进行的应用计算)。
Example:
例:
Give a list of numbers and we have to find their sum using lambda and reduce() function.
给出一个数字列表,我们必须使用lambda和reduce()函数找到它们的总和。
1) Approach 1: Using normal way
1)方法1:使用常规方法
# function to find sum of the elements
def add(data):
s=0
for n in data:
s=s+n
return s
# list of the values
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List :",fibo)
# function call
s=add(fibo)
print("Sum = ",s)
Output
输出量
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum = 143
2) Approach 2: Using reduce() with lambda
2)方法2:对lambda使用reduce()
from functools import reduce
def add(data):
s=0
for n in data:
s=s+n
return s
# list of integers
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List :",fibo)
# using reduce and lambda
s=reduce(lambda a,b:a+b,fibo)
print("Sum = ",s)
Output
输出量
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum = 143
翻译自: https://www.includehelp.com/python/lambda-and-reduce-with-example.aspx
lambda python