python 中: lambda

lambda 定义了一个匿名函数,是代码更简洁

lambda x:x+1

def g(x):
return x+1
是相同的哦。

python 中的map,filter, reduce 函数为序列内置函数
  • map根据提供的函数对指定序列做映射 map(function, sequence)->list 返回一个集合,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list

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

map(None,[1,3,5,7,9],[2,4,6,8,10])->[(1,2),(3,4),(5,6),(7,8),(9,10)]

print[x*2+10 for x in [1,2,3,4,5]]==print map(lambda x: x*2+10,[1,2,3,4,5])

  • filter 会起过滤作用

def is_even(x):

return x&1!=0

filter(is_even,[1,2,3,4,5,6,7])->[1,3,5,7]

filter(lambda x:x%3==0,[1,2,3,4,5,6])

  • reduce 进行累积作用

reduce (lambda x,y:x+y, [2,3,4,5,6],1) -> (((((1+2)+3)+4)+5)+6)

原文地址:https://www.cnblogs.com/fanhaha/p/7635645.html