码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2021-04-07 11:31:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:条件   end   efi   匿名函数   rom   ==   star   imp   fine   

匿名函数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()函数

 

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

标签:条件   end   efi   匿名函数   rom   ==   star   imp   fine   

原文地址:https://www.cnblogs.com/lp19910807/p/14622847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!