python中lambda表达式及高阶函数介绍

"""

lambda表达式,又叫匿名函数

格式: lambda 参数列表:表达式

"""

f = lambda x: x*2

r = f(2)

print(r)

上面的lambda表达式的功能相当于

def function(x):

  return x*2

#map函数

 map(function, inter1)  #map函数的第一个参数是一个函数,第二个参数是一个可迭代对象

map_demo = map(lambda x: 2*x, [1,2,3,4])

print(map_demo)

print(list(map_demo))

# out [2,4,6,8]

# map函数的功能就是把可迭代对象的每个元素值传给第一个参数中函数中进行计算,获得的每一个结果组成一个新的可迭代对象

print(list(map(str,[1,2,3,4]))

#out ['1','2','3','4']

#reduce函数

from functools import reduce

r = reduce(lambda x,y: x+y,[1,2,3,4])  #reduce函数的第一个参数是一个函数,第二个参数是一个可迭代对象

print(r)

#out 10

# reduce的计算过程是

"""

前一个元素计算的结果作为下一轮计算的第一个参数,再传入后一个参数进入第二个参数,依次进行,最后返回最终的结果

"""

# filter函数

print(list(filter(lambda x:x % 2 ==1, [1,2,3,4,5,6,7,8])))

# out [1,3,5,7]

#filter函数用来从可迭代对象中,根据函数功能来过滤出符合函数表达式中条件的元素,并返回。

print(list(filter(labmda x: x and x.strip(), ["adfa", "", "dg"]) #过滤掉列表中的空元素

# out ["adfa", "dg"]

猜你喜欢

转载自www.cnblogs.com/laofang/p/12093647.html