13.函数式编程:匿名函数高阶函数装饰器

Posted 邹柯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了13.函数式编程:匿名函数高阶函数装饰器相关的知识,希望对你有一定的参考价值。

# def add(x,y):
#     return x + y
# print(add(1,2))  # 3

# 匿名函数
# lambda表达式
# f = lambda x,y:x + y
# print(f(1,2)) # 

# 三元表达式
# x = 2
# y = 1
# r = x if x > y else  y
# print(r) # 2

 

# map

# list_x = [1,2,3,4,5,6,7,8]
# def square(x):
#    return x * x

# 方法1
# for x in list_x:
#     square(x)

# 方法2
# r = map(square,list_x)
# print(r)        # <map object at 0x029F31F0>
# print(list(r))  # [1, 4, 9, 16, 25, 36, 49, 64]

# r = map(lambda x:x*x,list_x)
# print(list(r))  # [1, 4, 9, 16, 25, 36, 49, 64]


# list_x = [1,2,3,4,5,6,7,8]
# list_y = [1,2,3,4,5,6,7,8]
# r = map(lambda x,y:x*x + y,list_x,list_y)
# print(list(r))  # [2, 6, 12, 20, 30, 42, 56, 72]


list_x = [1,2,3,4,5,6,7,8]
list_y = [1,2,3,4,5,6]
r = map(lambda x,y:x*x + y,list_x,list_y)
print(list(r))    # [2, 6, 12, 20, 30, 42]

 

#reduce

from functools import reduce

# 连续计算,连续调用lamdba
list_x = [1,2,3,4,5,6,7,8]
# r = reduce(lambda x,y:x+y,list_x)
# print(r)   # 36
# ((((((1+2)+3)+4)+5)+6)+7)+8
# x=1
# y=2

# x=(1+2)
# y=3

# x=((1+2)+3)
# y=4

# x=(((1+2)+3)+4)
# y=5
# ....

# [(1,3),(2,-2),(-2,3),...]

# r = reduce(lambda x,y:x+y,list_x,10)
# print(r)  # 46
# x=1
# y=10

# x=(1+10)
# y=2

# x=((1+10)+2)
# y=3

# x=(((1+10)+2)+3)
# y=4
# ....

 

# filter

list_x = [1,0,1,0,0,1]
# r = filter(lambda x:True if x==1 else False,list_x)
r = filter(lambda x:x,list_x)
print(list(r)) # [1, 1, 1]

list_u = [a,B,c,F,e]

 

# 装饰器

import time
def f1():
    print(this is a function_1)

def f2():
    print(this is a function_2)

def print_current_time(func):
    print(time.time())
    func()

print_current_time(f1)
# 1524300517.6711748
# this is a function_1
print_current_time(f2)
# 1524300517.6711748
# this is a function_2
def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

def f1():
    print(this is a function_1)
f = decorator(f1)
f()
# 1524301122.5020452
# this is a function_1
def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper
    
@decorator
def f3():
    print(this is a function_2)
f3()
# 1524301486.9940615
# this is a function_2

 

以上是关于13.函数式编程:匿名函数高阶函数装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Python基础笔记:函数式编程:高阶函数返回函数匿名函数装饰器偏函数

python3函数式编程:匿名函数高阶函数装饰器

python中的函数式编程与装饰器

Go的魅力, 函数式(柯里化, 闭包, 高阶函数), Python@装饰器, 封装

2.1python高级编程1-函数式编程和装饰器

python基本知识:函数式编程,装饰器