lambda的一般形式是关键字lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式。lambda是一个表达式而不是一个语句。它能够出现在Python语法不允许def出现的地方。作为表达式,lambda返回一个值(即一个新的函数)。lambda用来编写简单的函数,而def用来处理更强大的任务。
f = lambda x,y,z : x+y+z
print f(1,2,3)
g = lambda x,y=2,z=3 : x+y+z
print g(1,z=4,y=5)
输出结果:
6
10
filter():简单的理解为过滤器,需要两个参数,function,和一个序列(字符串、列表、元组都是序列),过滤器会依次将序列的值传入function中,如果返回True的话,将其重新生成一个列表返回。
1 list(filter(lambda x:True if x % 3 == 0 else False, range(100)))
2 [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
zip():字面意思理解,就是zip打包,可以将多个序列进行打包,它会将序列拆分,然后把第一个序列和第二个序列的元素依次组成元组,2个一组组合成列表。不过要注意的是,这是以最短序列来组合的,就是说如果一个序列比较长,一个比较短的话,组合只会进行到断序列的最后一个元素,多余的部分会被抛弃。
1 >>> str1 = "abcde"
2 >>> str2 = "abcdefg"
3 >>> list(zip(str1, str2))
4 [('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e')]
5 >>>for i in zip(*str1):
print(i)
6 ('a','b','c','d','e')
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
map():映射,用法和filter()类似,也是将序列放入函数进行运算,但是,不论运算结果为什么,map()都将忠实反馈,这是map()和filter()的主要区别。请注意,filter()和map()中的function都必要有一个返回值。
1 >>> list(map(lambda x:True if x % 3 == 0 else False, range(100)))
2 [True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True]
reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
>>> reduce(lambda x,y:x*10+y, [1, 3, 5, 7, 9])
13579
网友评论