Python:函数4——匿名函数和bif:map、filter

来源:互联网 发布:网络平台app代理 编辑:程序博客网 时间:2024/06/05 01:54

匿名函数lambda

>>> g = lambda x: 2 * x + 1>>> g(5)11>>> g = lambda x, y: x + y>>> g(3,4)7
好处:1、省定义过程,精简;2、调用次数少,省起名字;3、可读性强,不用跳读


两个牛逼bif

filter()叫做过滤器,把非True的能容过滤掉

help(filter):

filter(function or None, iterable) --> filter object

>>> filter(None, [1, 0, False, True])<filter object at 0x7feed39a6438>>>> list(filter(None, [1, 0, False, True]))[1, True]
>>> def odd(x):...     return x % 2... >>> show = filter(odd, range(10))>>> list(show)[1, 3, 5, 7, 9]>>> list(filter(lambda x: x % 2, range(10)))[1, 3, 5, 7, 9]

map()

map(func, *iterables) --> map object把每个iterable的元素都应用func函数返回

>>> list(map(lambda x: x * 2, range(10)))[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]



0 0
原创粉丝点击