关于java:拉钩Java工程师高薪训练营

10次阅读

共计 1035 个字符,预计需要花费 3 分钟才能阅读完成。

download:拉钩 Java 工程师高薪训练营

下崽 ZY:https://www.zxit666.com/4236/
匿名函数 (lambda 表达式)
在 Python 中,函数能够算的上是“一等公民”了,咱们先回顾下函数的长处:

缩小代码反复量
模块化代码

然而咱们有没有想过,如果咱们须要一个函数,比拟简短,而且只须要应用一次(无需反复调用),那还须要定义一个有名字的函数么?
答案是否定的,这里咱们就能够应用匿名函数来实现这样的性能。
咱们先看看求一个数的平方,咱们定义个函数怎么写:
def square(x):

return x**2

square(3)
复制代码
而 lambda 表达式就能够这样写:
square = lambda x: x**2
square(3)
复制代码
依据下面的例子,其实 lambda 表达式应用还是很简略的,如下:
lambda argument1, argument2,…..: expression
复制代码
接下来,介绍的 map、filter 和 reduce 函数,与 lambda 表达式联合应用,能力施展其弱小的作用了。
map 函数
map 函数的应用如下:
map(function, iterable)
复制代码
其作用是,对 iterable 的每个元素,都使用 function 这个函数,最初返回新的可遍历的汇合。
a = [1,2,3,4,5]
b = map(lambda x: x*2,a)
print(list(b))

[2, 4, 6, 8, 10]

复制代码
filter 函数
filter 函数的应用如下:
filter(function, iterable)
复制代码
其作用是,对 iterable 的每个元素,都使用 function 这个函数进行判断,最初返回全副为 True 的新的可遍历的汇合。
a = [1,2,3,4,5,6]
b = filter(lambda x :x%2 ==0, a)
print(list(b))

[2, 4, 6]

复制代码
reduce 函数
reduce 函数的应用如下:
reduce(function, iterable)
复制代码
function 规定有两个参数,示意对 iterable 每个元素和上一次运算的后果,进行 function 运算,最初失去一个值,这里要留神,咱们须要从 functools 中导入 reduce。
from functools import reduce

a = [1,2,3,4]
b = reduce(lambda x,y: x*y,a)
print(b)

24 123*4

复制代码
总结

lambda 表达式
map、filter 和 reduce 函数

正文完
 0