1. 程式人生 > >13.函數式編程:匿名函數、高階函數、裝飾器

13.函數式編程:匿名函數、高階函數、裝飾器

裝飾 style print from int class for 調用 add

# 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.函數式編程:匿名函數、高階函數、裝飾器