人若有情死得早 发表于 2017-6-26 21:37:43

021函数:lambda表达式

1.lambda表达式的作用
1)Python写一些执行脚本时,使用lambda就可以省下定义函数过程,比如说我们只是需要写个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后再写调用,使用lambda就可以使得代码更加精简;
2)对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字也是比较头疼的问题,使用lambda就不需要考虑命名的问题了;
3)简化代码的可读性,由于普通的屌丝函数阅读经常要调到开头def定义部分,使用lambda函数就可以省去这样的步骤;
>>> def ds(x):
        return 2 * x + 1

>>> ds(5)
11
>>> lambda x : 2 * x + 1
<function <lambda> at 0x013E5300>
>>> g = lambda x : 2 * x + 1
>>> g(5)
11
>>> def add(x,y):
        return x + y

>>> add(3, 4)
7
>>> lambda x, y : x + y
<function <lambda> at 0x0229CDF8>
>>> g = lambda x, y : x + y
>>> g(3, 4)
7
2.filter()——过滤器
>>> 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.
filter()有两个参数,第一个参数可以是一个函数也可以是None对象,第二个参数是一个可迭代的数据;如果第一个参数是一个函数的话,则将第二个可迭代数据里的每一个元素作为函数的参数计算,把返回Ture的值筛选出来并成立一个列表;如果第一个参数为None,则将第二个参数里面True的值筛选出来。
>>> filter(None, )
<filter object at 0x003BACF0>
>>> list(filter(None, ))

过滤奇数的普通写法:
>>> def odd(x):
        return x % 2

>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)

使用lambda()函数的写法:
>>> list(filter(lambda x : x % 2, range(10)))

3.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.
map()这个内置函数有两个参数,一个是函数,一个是可迭代的序列;功能是:将序列的每一个元素作为函数的参数进行运算加工,直到可迭代序列的每一个元素都加工完毕返回所以加工后的元素构成的新序列。
>>> list(map(lambda x : x * 2, range(10)))
页: [1]
查看完整版本: 021函数:lambda表达式