notes: 参考文档 -(菜鸟教程)http://www.runoob.com/python/python-built-in-functions.html
参考文档 -(妖白)http://blog.csdn.net/qq_24753293/article/details/78337818
一. lambda()
描述:
简化 def 函数
实例:
A=lambda x:x+1
理解为:
- def A(x):
- return x+1
冒号左边想要传递的参数
冒号右边想要得到的数(可能带表达式)
二. map()
描述:
map(function, iterable, ...)会根据提供的函数对指定序列做映射, 返回迭代器
实例:>>>def square(x) : # 计算平方数
- ... return x ** 2
- ...>>> list(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方
- [1, 4, 9, 16, 25]>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数
- [1, 4, 9, 16, 25]
- # 提供了两个列表, 对相同位置的列表数据进行相加>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
- [3, 7, 11, 15, 19]
- # 如果函数有多个参数, 但每个参数的序列元素数量不一样, 会根据最少元素的序列进行:>>> listx = [1,2,3,4,5,6,7] # 7 个元素>>> listy = [2,3,4,5,6,7] # 6 个元素>>> listz = [100,100,100,100] # 4 个元素>>> list_result = map(lambda x,y,z : x**2 + y + z,listx, listy, listz)>>> print(list(list_result))
- [103, 107, 113, 121]
三. filter()
描述:
filter(function, iterable) 函数用于过滤序列, 过滤掉不符合条件的元素, 返回由符合条件元素组成的新迭代器
实例:
- # 只有序列中的元素执行函数 (is_odd) 为 true 时, 才被用于构建新的迭代器>>> def is_odd(n):
- ... return n%2 == 1
- ...>>> newlist = filter(is_odd,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])>>> print(newlist)
- <filter object at 0x00000227B33F8198>>>> print(list(newlist))
- [1, 3, 5, 7, 9]
- # 用 map 函数模仿 filter
- list(map(lambda x:x-5 if x>5 else x,[4,5,6]))
- [4, 5, 1]
- # 理解: if 为 true, 执行 lambda 表达式, if 为 false, 执行 else 表达式
- # 用 map 函数模仿 filter, 必须要有 "else">>> list(map(lambda x:x-5 if x>5 ,[4,5,6]))
- File "<stdin>", line 1
- list(map(lambda x:x-5 if x>5 ,[4,5,6]))
- ^
- SyntaxError: invalid syntax
来源: http://www.bubuko.com/infodetail-2532520.html