美文网首页
python基础知识(四)--函数式编程

python基础知识(四)--函数式编程

作者: Godric_wsw | 来源:发表于2018-09-01 16:38 被阅读11次

    1. 迭代器

    #iteration
    def fib(n):
        #迭代初始值
        a = 0
        b = 1
        #迭代表达式
        for i in range(n):
            yield a+b
            a,b = b, a+b
    
    for i in fib(10):
        print(i)
    

    2.递归

    #recursion
    def fib(n):
        #递归终止条件
        if n == 1:
            return 1
        elif n == 0:
            return 0
        #递归表达式
        return fib(n-1) + fib(n-2)
    print(fib(10))
    

    3.Lamada

    a = lambda x,y: x+y
    print(a(1,2))
    

    4.Map

    lst1 = [1,2,3]
    lst2 = [4,5,6]
    lst3 = [7,8,9,10]
    b = map(lambda x,y,z:str(x)+str(y)+str(z),lst1,lst2,lst3)
    for i in b:
        print(i)
    

    5.装饰器

    #带有不定参数的装饰器
    import time
    def deco(func):
        def wrapper(*args, **kwargs):
            startTime = time.time()
            func(*args, **kwargs)
            endTime = time.time()
            msecs = (endTime - startTime)*1000
            print("time is %d ms" %msecs)
        return wrapper
    
    @deco
    def func(a,b):
        print("hello,here is a func for add :")
        time.sleep(1)
        print("result is %d" %(a+b))
    
    if __name__ == '__main__':
        f = func(3,4)
    

    相关文章

      网友评论

          本文标题:python基础知识(四)--函数式编程

          本文链接:https://www.haomeiwen.com/subject/cajuwftx.html