码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-04-21 17:48:12      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:current   function   lte   函数   高阶函数   span   map   class   func   

# 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.函数式编程:匿名函数、高阶函数、装饰器

标签:current   function   lte   函数   高阶函数   span   map   class   func   

原文地址:https://www.cnblogs.com/zouke1220/p/8902030.html

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