python中的filter, map内置函数

filter, map内置函数

filter

>>> a = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> a
<filter object at 0x7f53c34afa90>
>>> print(list(a))
[2, 4, 6, 8, 10]

filter(function, iterable)是一个用于过滤的内置函数.

返回一个过滤后的可迭代对象.

filter会根据处理函数的返回值的真假来决定返回的可迭代对象中的值.

map

>>> a = map(lambda x: x+1, [1, 2, 3])
>>> a
<map object at 0x7f53c349e6d8>
>>> print(list(a))
[2, 3, 4]

map(function, iterable)是一个将可迭代对象中的元素传给指定函数处理的内置函数.

返回一个处理后的可迭代对象.

map会把传入的iterable对象中的元素逐个传入指定的function对象中处理, 将处理后返回的结果保存到一个iterable对象中.


猜你喜欢

转载自blog.csdn.net/One_of_them/article/details/83093583