python中的map,filter,zip函数

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}]

 

posted @ 2016-03-02 22:04  木羊羊羊  阅读(1222)  评论(0编辑  收藏  举报