1.lambda 匿名函数
>>> f = lambda x:x**3 #(.*):(.*) ,\1是函数参数 \2是返回值
>>> f(2)
8
>>> f(3)
27
>>> (lambda x,y:x+y)(10,20) # lambda另一种形式
30
>>> (lambda x:x%2 == 0)(4) # 涉及判断,返回结果为True or False
True
>>> (lambda x:x%2 == 0)(3)
2.map(function,sequence) # 列表的函数化映射
>>> def sayHello(name):
... return 'hello' + ' ' + name
...
>>> map(sayHello,['xiaot','xiaoq','lili'])
['hello xiaot', 'hello xiaoq', 'hello lili'] #列表同时操作!
>>>
>>> map((lambda x:x**3),range(5)) #这里也可以用lambda
[0, 1, 8, 27, 64]
>>> map((lambda x,y:x+y),[1,2,3],[4,5,6]) #函数多个参数时,是从不同列表取参!
[5, 7, 9]
>>> map(None,['a','b','c'],['d','e','f'],['g','h','i']) #一个比较特殊的用法,多个列表对应的列组成元组
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> def abc(a,b,c):
... return a*100 + b*10 + c
...
>>> list1 = [ 1, 2, 3]
>>> list2 = [ 4, 5, 6]
>>> list3 = [ 7, 8, 9]
>>> [abc(a,b,c) for a in list1 for b in list2 for c in list3 ] #这里的for是一种递归相当于for a in list1{for b in list2{for c in list3}}
[147, 148, 149, 157, 158, 159, 167, 168, 169, 247, 248, 249, 257, 258, 259, 267, 268, 269, 347, 348, 349, 357, 358, 359, 367, 368, 369]
>>> map(abc,list1,list2,list3) #map的话,就可以并行操作!
[147, 258, 369]
3.reduce (function,sequence) # 累积操作,函数每次只操作两个参数,返回的参数再与接下去的一个参数进行操作,直到完成!
>>> def sum(x,y):
... return x+y
...
>>> reduce(sum,range(10))
45
>>> reduce((lambda x,y:x+y),['a','b','c','d','e','f','g'])
'abcdefg'
4.filter (function,sequence) # filter 过滤出函数返回值为真的列表
>>> def even(x):
... return x%2 == 0
...
>>> even(2)
True
>>> filter(even,range(20)) #过滤偶数列表
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
>>> filter((lambda x:x%2 != 0),range(20)) #过滤奇数列表
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
参考:
http://my.oschina.net/zyzzy/blog/115096
http://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html