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

python中的map,filter,zip函数

时间:2016-03-02 23:31:39      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

map()

Return an iterator that applies function to every item of iterable, yielding the results

例如:

a = map(lambda x:x**2 ,[1,2,3])
print([b for b in a])

结果:

[1, 4, 9]

或者:

a = map(lambda x,y:x+y ,[1,2,3],[1,2])
print([b for b in a])

结果:

[2, 4]

 

filter(functioniterable)

Construct an iterator from those elements of iterable for which function returns true.If function is None, all elements of iterable that are false are removed

例子:

a = filter(lambda x:x>2, [1,2,3])
print([b for b in a])

或者 function is None:

a = filter(None,[1,2,0,-1])
print([b for b in a])

结果:

[1, 2, -1]

 

zip()

Make an iterator that aggregates elements from each of the iterables

例子

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
zipped = list(zipped)
print(zipped)

结果

[(1, 4), (2, 5), (3, 6)]

 

dict()

>>> a = dict(one=1, two=2, three=3)
>>> b = {one: 1, two: 2, three: 3}
>>> c = dict(zip([one, two, three], [1, 2, 3]))
>>> d = dict([(two, 2), (one, 1), (three, 3)])
>>> e = dict({three: 3, one: 1, two: 2})
>>> a == b == c == d == e
True

 

一个综合的例子

a = map(lambda x: dict(zip([number], [x])),filter(lambda x: x > 3, [1,2,3,4,5,6]))
print([b for b in a])

结果

[{number: 4}, {number: 5}, {number: 6}]

 

python中的map,filter,zip函数

标签:

原文地址:http://www.cnblogs.com/duyang/p/5236690.html

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