python的lambda、filter、map、reduce表达式

个人博客,欢迎来撩 fangzengye.com

Lambda函数也称匿名函数,相比于def,lambda无需定义函数,方便快速定义函数,不用担心函数名冲突

看看def和lambda的区别

def g(x):
    return x+1
g = lambda x:x+1

使用

print(g(2))
3

不难可以看出lambda更加简洁

filter

foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]

filter:过滤,指返回符合条件的值

filter+lambda结合使用,filter(lambda判断条件,参数变量列表)返回对列表中每个元素经过函数运算判断为True返回的列表

Filter使用生成器简化后的代码

print [x for x in foo if x % 3 == 0]

map

print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]

map:映射,指返回每个元素经过函数运算之后的值

map+lambda结合使用,map(lambda运算规则,参数变量列表)

Map使用生成器简化后的代码

print [x * 2 + 10 for x in foo]

reduce

print reduce(lambda x, y: x + y, foo)
139

reduce

 

https://www.cnblogs.com/caizhao/p/7905094.html

https://www.cnblogs.com/LQ6H/p/12940519.html

 

 

 

 

 

 

posted @ 2020-12-13 14:53  开源的Boy  阅读(71)  评论(0)    收藏  举报