Python的filter, map, reduce, lambda

1. filter(function, sequence)
Do function(item) for the item of sequence
return the item whose result is True.

def f(x):
    return x % 3 != 0 and x % 4 != 0
filter(f, range(2, 25))
Out[34]: [2, 5, 7, 10, 11, 13, 14, 17, 19, 22, 23]
2. map(function, sequence, [sequence])
Do function(item) for the item of sequence
return a list with the excute result

def f(x):
    return x*x*x
map(f, range(1, 15))
Out[35]: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744]
def f(x, y):
    return x+y
map(f, range(9), range(9))
Out[36]: [0, 2, 4, 6, 8, 10, 12, 14, 16]
3. reduce(function, sequence, starting_value)
def f(x,y):
    return x+y

reduce(f, range(1, 15))
Out[38]: 105
reduce(f, range(1, 15), 20)
Out[39]: 125
4. lambda
f = lambda x: x * 3
f(3)

or
(lambda x: x * 3)(3)
Out[42]: 9
5. lambda & reduce, lambda & map
map(lambda x, y: x + y, [1,3,5], [2,4,6])
Out[44]: [3, 7, 11]
map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6])
Out[45]: [(3, -1), (7, -1), (11, -1)]
reduce((lambda x,y: x+y), range(5))
Out[46]: 10



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值