python之常用内置函数(map,filter,lambda)

map函数

语法

map(function, iterable, …)

参数

function: 函数
iterable: 一个或多个序列

实例1

def square(x):
	return x ** 2
map (square, [1,2,3,4,5]) #输出结果为 [1,4,9,16,25]

实例2

 #使用lambda匿名函数
map(lambda x :  x** 2, [1,2,3,4,5,6] )# 输出结果为 [1,4,9,16,25,36]

filter函数

描述:filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

语法

filter(function, iterable, …)

参数

function: 函数
iterable: 一个或多个序列

实例

def is_odd(n):
    return n % 2 == 1
    
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])# 输出结果为[1,3,5,7,9]

猜你喜欢

转载自blog.csdn.net/wangliu123789/article/details/88943931