Python中filter()和map()函数用法

温故而知新~~~

filter()函数

filter(function, iterable)
  • function – 判断函数
  • iterable – 可迭代对象

例子

input = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print(list(filter(lambda x: x % 3 == 0, input)))
>>[18, 9, 24, 12, 27]

过滤出所有input中能被3整除的数

如果不用lambda方法,可以自定义函数,比如:

def X2(x):
    return x % 2 == 0

input = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print(list(filter(X2, input)))

过滤出input中能被2整除的数。

注意:参数function是判断函数!即True or False

map()函数

根据给定函数对指定序列做映射

map(function, iterable, ...)
  • function – 函数
  • iterable – 一个或多个序列

例子

def X2(x):
    return x**2

input = [1,2,3,4,5]
print(list(map(X2, input)))
>>[1, 4, 9, 16, 25]

注意:参数function只是一个函数名即可!!

或者使用lambda方法

input = [1,2,3,4,5]
print(list(map(lambda x:x**2, input)))
>>[1, 4, 9, 16, 25]

也可以传入多个序列,此时函数对每个序列的相同位置操作

input1 = [1,2,3,4,5]
input2 = [7,8,9,0,6]
print(list(map(lambda x, y:x + y, input1, input2)))
>>[8, 10, 12, 4, 11]

如果两个序列长度不一致,会以最短序列为准

input1 = [1,2,3,4,5]
input2 = [7,8,9,0,6,10]
print(list(map(lambda x, y:x + y, input1, input2)))
>>[8, 10, 12, 4, 11]
原创文章 96 获赞 24 访问量 3万+

猜你喜欢

转载自blog.csdn.net/c2250645962/article/details/105715276