码迷,mamicode.com
首页 > 编程语言 > 详细

filter,map,reduce,lambda(python3)

时间:2016-04-09 23:17:49      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

1.filter

filter(function,sequence)

对sequence中的item依次执行function(item),将执行的结果为True(符合函数判断)的item组成一个list、string、tuple(根据sequence类型决定)返回。

 1 #!/usr/bin/env python
 2 # encoding: utf-8
 3 """
 4 @author: 侠之大者kamil
 5 @file: filter.py
 6 @time: 2016/4/9 22:03
 7 """
 8 #filter map reduce lambda
 9 def f1(x):
10     return x % 2 != 0 and x % 3 != 0
11 a = filter(f1, range(2,25))
12 print(a)#<filter object at 0x7f7ee44823c8>
13 #这种情况是因为在3.3里面,filter()的返回值已经不再是list,而是iterators.
14 print(list(a))
15 def f2(x):
16     return x != "a"
17 print(list(filter(f2,"dfsafdrea")))

结果:

ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/fmrl.py
<filter object at 0x7f4d1ca5e470>
[5, 7, 11, 13, 17, 19, 23]
[d, f, s, f, d, r, e]

Process finished with exit code 0

2.map

语法与filter类似

 1 #!/usr/bin/env python
 2 # encoding: utf-8
 3 """
 4 @author: 侠之大者kamil
 5 @file: map.py
 6 @time: 2016/4/9 22:22
 7 """
 8 def cube(x):
 9     return x * x *x
10 a = map(cube,range(10))
11 print(list(a))
12 def add(x,y,z):
13     return x + y +z
14 b = map(add,range(5),range(5),range(5))
15 print(list(b))

 结果:

ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/map.py
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
[0, 3, 6, 9, 12]

Process finished with exit code 0

3.reduce

reduce已经取消了,如想使用,可以用fuctools.reduce来调用。但是要先导入fuctools, 即输入:import fuctools 

4.lambda

快速定义最小单行函数

1 g = lambda x:x *2
2 print(g(5))
3 print((lambda x:x *2)(5))

结果:

10
10

 

filter,map,reduce,lambda(python3)

标签:

原文地址:http://www.cnblogs.com/kamil/p/5372909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!