lambda表达式
Python允许使用lambda关键字来创建匿名函数,那什么是匿名函数,匿名函数和普通的函数又有什么不同呢?使用匿名函数有哪些优势呢?
首先定义一个普通函数
>>> def dx(x):
return 2*x+1
>>>
>>> dx(5)
11
接下来定义匿名函数,语法精简。
>>> lambda x : 2*x+1
<function <lambda> at 0x01E11CD8>
>>> g = lambda x : 2*x + 1
>>> g(5)
11
>>>
lambda后面加上普通函数的形参 ,冒号后面跟上普通函数的返回值。不用定义函数,不用考虑申请和释放资源。
多个参数
>>> g = lambda x,y:x+y
>>> g(3,4)
7
>>>
是不是很精简!!!
lambda表达式的作用
1、Python写一些执行脚本时,使用lambda就可以省下定义函数的过程,比如说我们需要写个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后在写调用,使用lambda就可以使得代码更加精简。
2、对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字也是比较头疼的问题,使用lambda就不需要考虑命名的问题了。
3、简化代码的可读性
两个牛逼的BIF(内置函数):filter()和map()
filter() 过滤器
>>> filter(None,[1,0,False,True])
<filter object at 0x02292C30>
>>> list(filter(None,[1,0,False,True]))
[1, True]
>>>
>>> def odd(x):
return x%2
>>> temp = range(10)
>>> show = filter(odd,temp)
>>> list(show)
[1, 3, 5, 7, 9]
>>>
filter()和lambda的结合
>>> list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]
>>>
filter()函数的帮助文档,filter()函数有两个参数,第一个参数可以为函数名称或None,第二个参数为一个有效迭代量。
当第一个参数为function名称时,返回的是:过滤function函数执行iterable后的结果为True部分,结果是一个对象。
当第一个参数为None时,返回的是iterable中值为真的部分集合。
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
map()
>>> list(map(lambda x:2*x,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
多个参数
>>> list(map(lambda x,y:x+y,range(10),range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
map()函数的第二个参数,是收集参数,收集参数的个数应该和前面函数的参数个数一致,且每个收集参数的元素个数和类型应正确。
>>> help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.