lambda python_Python | Lambda和reduce()与示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值