python中的map,filter,zip函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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}]

 

以上是关于python中的map,filter,zip函数的主要内容,如果未能解决你的问题,请参考以下文章

Python---高级函数map, filter, zip, enumerate等的用法

lambda 匿名函数,map,filter,reduce,zip,介绍

Python 内置函数 -- zip(), sorted(), filter()和map()

python的reduce,map,zip和filter函数

python---------匿名函数(map,filter,zip..)

好好学python · 内置函数(range(),zip(),sorted(),map(),reduce(),filter())