Python基础(3)- lambda表达式

浏览: 1742

这里简单整理下,lambda表达式相关内容。

1.什么是lambda表达式

    lambda表达式,是一个匿名函数,用起来方便快捷一些

#lambda 参数:操作(参数)

fun_add = lambda x: x+1

print(fun_add(1))
print(fun_add(10))

这里,一个简单的加1的函数,看起来也很直观

fun_add = lambda x,y: x+y

print(fun_add(3,4))
print(fun_add(8,9))

这是x+y的函数,的确简洁很多

看网上,提到lambda表达式的话,都会提到函数式编程,一些常用的函数,像map,reduce,filter,sorted,


2.map函数

map是Python内置的一个函数,接收2个参数,一个函数,一个或多个可迭代参数

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
d1 = [1,2,3,4,5]

def add(x):
return x+10

t = map(add , d1)
print('原来的list:',d1)
print('执行add后的list:',list(t))

我们定义了一个函数,对传入的参数加10,一个list

image.png

map把这个函数,作用在每一个list的元素上,

这里呢,我们就可以用lambda表达式写,方便又直观

d1 = [1,2,3,4,5]
t = map(lambda x: x+10 , d1)
print('原来的list:',d1)
print('执行add后的list:',list(t))

我们也可以传2个list,这里会计算2个list的和

s1 = [1,2,3]
s2 = [4,5,6]
t = map(lambda x,y: x+y,s1,s2)
print(list(t)) ##[5, 7, 9]

2. reduce函数

reduce会将function作用于sequence,function接收2个参数

    reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
t = reduce(lambda x,y: x+y, [1,2,3])
print(t) #6,((1+2)+3)=6

t = reduce(lambda x,y: x*10+y,[1,2,3])
print(t) # ((1*10+2)*10+3)=123

3. filter函数

看名字,就是一个过滤的功能,对每个item调用function,只返回为True的

 |  filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
t = filter(lambda x: x<0,range(-5,5))
print(list(t)) #[-5, -4, -3, -2, -1]
推荐 1
本文由 liutangwow 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

1 个评论

布局很不错

要回复文章请先登录注册