python自动化2021/04 匿名函数 高阶函数

匿名函数lambda:

 

# def foo(x,y):
# return x+y
#
# foo(12,4)
#python的匿名函数: lambda 参数:函数体
# print((lambda x,y:x+y)(12,4))

a = [1,2,3,4,5,6]

# def foo(x):
# return x % 2 == 0
#filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
# print(list(filter(foo,a)))

# print(list(filter(lambda x:x % 2 == 0,a)))

# print(list(filter(lambda x:x>2 ,[1,2,3,4]))) #[3, 4]
#map
# print(list(map(lambda x:x+2 ,[1,2,3,4]))) #[3, 4, 5, 6]
# print(list(map(lambda x,y:x+y ,[1,2,3,4],[5,6,7,8]))) #[6, 8, 10, 12]
#reduce 函数会对参数序列中元素进行累积


from functools import reduce
print(reduce(lambda x,y:x+y,[1,2,3,4,5]))


高阶函数:
'''

高阶函数:
1 形参为函数的函数
2 返回值为函数的函数

'''
#一切皆数据,函数亦是变量。

# def foo():
# print("foo")
# foo = 10
# print(food()) #NameError: name 'food' is not d efined


#1 形参为函数的函数

# def bar():
# print("bar")
# def foo():
# print("foo")
#
# def func(f):
# f()
#
# func(bar)


#案例;计时案例
#方式 1
import time
print(time.time())
def bar():
print("bar功能")
def foo():
start = time.time()
print("foo功能")
time.sleep(2)
end = time.time()
print("花费时间:",end-start)
foo()

#方式 2

def bar():
print("bar功能")
time.sleep(3)
def foo():
print("foo功能")
time.sleep(2)

def timer(func):
start = time.time()
func()
end = time.time()
print("花费时间:", end - start)

timer(foo)
timer(bar)


def foo():
def bar():
print("alex")
return bar

func = foo() #相当于把return的bar值给了func 指向了同一块内存地址
func() #相当于调用了bar()函数

 

posted @ 2021-04-06 17:30  lpaxq  阅读(53)  评论(0编辑  收藏  举报