python lambda介绍

1.lambda是什么
lambda声明了一个匿名函数, 指令格式为:
lambda 参数:函数体,返回值为函数体表达式值
等价于:
function(参数){
return 函数体表达式
}

使用示例如下:

foo = lambda x:x+1
print("lambda匿名函数:%s" % foo(1))

def foo(x):
    return x+1
print("普通函数:%s" % foo(1))

运行结果:

2.filter全局函数
作用:过滤列表
指令格式为:filter(function, iterable)
参数:function--判断函数
iterable--可迭代对象
返回值:返回filter对象

使用示例:

def is_divided(x):
    if x%3 == 0:
        return True
    else:
        return False
foo = [1,2,3,4,5,6,7,8,9]
result = filter(is_divided, foo)
print(result)
print(type(result))
print(next(result))

运行结果:

python3与python2的区别在于,python2中filter返回列表,而python3返回filter对象。
filter类实现了__iter__和__next__方法,可以看成一个迭代器,有惰性运算的特征,相对python2提高了性能,可以节约内存。

也可以使用lambda匿名函数实现,代码如下:

foo = [1,2,3,4,5,6,7,8,9]
result = filter(lambda x:x%3==0, foo)
print(result)
print(type(result))
print(next(result))

3.map全局函数
作用:根据提供的函数对指定序列做映射
指令格式:map(function, iterable)
参数:function--函数
iterable--可迭代对象
返回值:迭代器对象

使用示例:

def double_num(x):
    return x*2
foo = [1,2,3,4,5,6,7,8,9]
result = map(double_num, foo)
print(result)
print(type(result))
print(next(result))

运行结果:

和filter函数类似,map函数返回值为一个map类型对象,也是一种迭代器类型
区别在于fileter函数function参数,执行结果返回bool型

使用lambda匿名函数,代码如下:

foo = [1,2,3,4,5,6,7,8,9]
result = map(lambda x:x*2, foo)
print(result)
print(type(result))
print(next(result))

4.reduce全局函数
作用:对列表中的元素进行累计
语法:reduce(function, iterable)
参数:function--函数,有两个参数
iterable--可迭代对象
返回值:返回计算结果

使用示例:

from functools import reduce

def add(x, y):
    return x+y

foo = [1,2,3,4,5,6,7,8,9]
result = reduce(add, foo)
print(result)
print(type(result))

运行结果:

reduce函数,function参数将执行结果作为下一次执行的x值,列表中下一个元素作为y值,递归计算。
在python3中需要引入from functools import reduce,才能使用reduce函数

使用lambda匿名函数,代码如下:

from functools import reduce
foo = [1,2,3,4,5,6,7,8,9]
result = reduce(lambda x,y:x+y, foo)
print(result)
print(type(result))

5.filter,map,reduce替代
filter,map,reduce的优点是代码简洁,但易读性较差
可以使用python的for..in..if语法来替代

foo = [1,2,3,4,5,6,7,8,9]
result = [x for x in foo if x%3==0]
print(result)
result = [x*2 for x in foo]
print(result)

运行结果:

6.总结
lambda大量简化了代码,但一定程度上降低了程序可读性,在能使用for..in..if来完成时,应避免使用lambda
lambda主要是为了减少单行函数的定义而存在的。

猜你喜欢

转载自www.cnblogs.com/shijingjing07/p/9045943.html