python 允许使用lambda表达式来创建匿名函数
lambda表达式
>>>def ds(x):
... return 2 * x +1
...
>>> ds(5)
11
>>>lambda x : 2* x +1
at 0x7f5f41b05d90>
>>> g = lambda x :2 * x +1
>>>g(5)
11
>>> def add(x,y):
... return x + y
...
>>> g = lambda x,y : x + y
>>> g(5,6)
11
>>> add(5,6)
11
lambda表达式的作用
Python写一些执行脚本时,使用lambda就可以生肖定义函数过程,比如说 我们只是需要写个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后再写调用,使用lambda就可以使得代码更加简单。
对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字也是比较头疼的问题,使用lambda就不需要考虑命名的问题了。
简化代码的可读性,由于普通的函数阅读经常要跳到开头def定义部分,使用lambda函数可以省区这样的步骤。
两个流弊的BIF
filter() 过滤器
help(filter)
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.
|
>>>filter(None,[1, 0, False, True])
>>>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]
>>> list(filter(lambda x : x %2, range(10)))
[1, 3, 5, 7, 9]
map() 影射,加工序列中的每一个元素,返回一个新的序列
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]