understand filter, map, and reduce function in Python

lambda

Before introducing the following three advanced functions, let’s focus on lambda. Lambda is a kind of anonymous function, which is widely used in functional programming. Let’s view some examples.

def sum1(x,y):
	return x+y
print(1,2) # res: 3
sum2 = lambda x,y: x+y
print(1,2) # res: 3

The above sum1 and sum2 have same function. They both return the sum of two arguments.


1. filter(func, seqs)

2. map(func, seqs)

3. reduce(function, seqs)

EXAMPLE

print(list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
print(list(map(lambda x: pow(x,2),[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
print(reduce(lambda x,y:x+y,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

EXAMPLE RESULT:

[1, 3, 5, 7, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
55
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值