匿名函数

1. 跟map结合使用

 1 >>> res = map(lambda n:n>5,range(10))
 2 >>> for i in res:
 3 ...   print(i)
 4 ...
 5 False
 6 False
 7 False
 8 False
 9 False
10 False
11 True
12 True
13 True
14 True
15 >>>
16 >>> res = map(lambda n:n*n,range(10))
17 >>> for i in res:
18 ...   print(i)
19 ...
20 0
21 1
22 4
23 9
24 16
25 25
26 36
27 49
28 64
29 81

 

2. 跟filter结合使用:

 1 >>> filter(lambda n:n>5,range(10))
 2 <filter object at 0x0000018C6879E588>
 3 >>>
 4 >>> res = filter(lambda n:n>5,range(10))
 5 >>> for i in res:
 6 ...   print(i)
 7 ...
 8 6
 9 7
10 8
11 9

 

3. 跟 reduce 结合使用

1 >>> import functools
2 >>> res = functools.reduce( lambda x,y:x+y,range(10))
3 >>> print(res)
4 45

 

posted @ 2017-08-15 19:18  炉山假面目  阅读(119)  评论(0)    收藏  举报