高阶函数及装饰器

内置高阶函数_map_reduce

高阶函数: 实参可以是一个函数; 返回值可以是一个函数;
普通函数:
# 函数定义:
        def 函数名(形参):   def add(a, b):
            函数体
            return 返回值   return 1
# 调用函数;
    函数名(实参)     add(1,2)
    print(函数名(实参) )
# print(abs(-5))
# a = abs
# print(a(-5))
# 内置高阶函数
# 1. map函数理解
from collections import Iterable
# def func(x):
#     return x**2
# f = map(func, [0,1,2,3,4])
# # print(isinstance(f, Iterable))
# for i in f:
#     print(i)
# 1. map函数练习
# 需求: 用户接收一串数字; '1 3 5 7 8', 将该字符串中的所有数字转化为整形,并以列表格式输出;
s = '1 3 5 7 8'
# a, b, c, d, e = list(map(int, s.split()))
# print(a,e)

print([int(i) for i in s.split()])

高阶函数及装饰器

# reduce: python2.x有, python3.x取消
# reduce在python3.x不是内置高阶函数, 而是需要导入from functools import reduce;
# In [2]: def add(x,y):
#    ...:     return x+y
#    ...:
# In [3]: reduce(add, [1,2,3,4,5,6])
# Out[3]: 21
# In [4]: (((1+2)+3)+4)
# from functools import reduce
# # def add(x,y):
# #     return x+y
# # print(reduce(add, range(5)))
# # 需求: 用户输入数字n; 求n的阶乘;  5!= 1*2*3*4*5
# def func(x,y):
#     return x*y

# print(reduce(func, range(1,6)))   # func(func(1,2),3)

高阶函数_filter_sorted

# filter高阶函数: filter(func, iterable)
#   1. func: 只有一个形参, 函数的返回值只能是True或者False;
def isodd(num):
    if num %2 == 0:
        return True
    else:
        return False
print(list(filter(isodd, range(10))))
def isPrime(num):
    pass
print(list(filter(isPrime, range(1000))))

# sorted:
# 排序: 由大到小
print(sorted([23,56546,78]))

# 排序: 由小到大, reverse=True, 代表排序后进行反转;
print(sorted([23,56546,78], reverse=True))

info = [
    ['001', 'apple', 1000, 2],
    ['002', 'xiaomi', 10, 2000],
    ['003', 'Oppo', 200, 1900],
    ['004', 'computer', 900, 5000]
]
def sorted_by_count(item):
    return item[2]
print(sorted(info, key=sorted_by_count))
# 需要按照商品的价格进行排序, 最终显示价格最高的商品名称和商品数量;
def sorted_by_price(item):
    return item[-1]
sorted_by_price_info = sorted(info, key=sorted_by_price)
print(sorted_by_price_info[-1][1], sorted_by_price_info[-1][2])

info = {
    '001':{
        'name':'apple',
        'count':1000,
        'price':2
    },

    '002': {
        'name': 'xiaomi',
        'count': 10,
        'price': 2000
    },
    '003': {
        'name': 'Oppo',
        'count': 200,
        'price': 1900
    }
}

def dict_sorted_by_count(item):
    return item['count']

print(sorted(info.values(), key=dict_sorted_by_count))

高阶函数及装饰器

sorted函数应用_携程笔试_移动数组中的0

(2018-携程-春招题)题目需求:
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
    第一行是数组长度, 后续每一行是数组的一条记录;
    4
    0
    7
    0
    2
# 输出:
    调整后数组的内容;
    7
    2
    0
    0
"""

n = int(input("数组长度:"))
li = [int(input()) for i in range(n)]
for i in sorted(li, key=lambda x: 1 if x is 0 else 0): print(i)
# def move_zero(item):
#     if item == 0:
#         return 1
#     else:
#         return 0
# for i in sorted(li, key=move_zero):

#     print(i)

高阶函数及装饰器

匿名函数
 1. 匿名函数的关键字为  lambda, 冒号前面是形式参数, 冒号后面是返回值;
#   2. 匿名函数的形式参数可以是: 必选, 默认, 可变, 关键字参数
"""
# 1). 无参数
f = lambda : "hello"

print(f())

f1 = lambda x, y=2: x**y
print(f1(2))
print(f1(2,3))

f2 = lambda  *args: sum(args)
print(f2(1,2,3,4,5))

f3 = lambda  **kwargs: kwargs
print(f3(a=1, b=2))

f4 = lambda x,y=2,*args,**kwargs: (x,y,args,kwargs)
print(f4(2,3,4,5,a=1,b=2))

from functools import reduce
def add(x, y):
    return x + y
# myadd = lambda x,y:x+y
# print(myadd(1,2))
print(reduce(lambda x, y: x + y, range(5)))

def mypow(x):
    return x ** 2
print(list(map(lambda x: x ** 2, range(5))))

# def isodd(num):
#     if num %2 == 0:
#         return True
#     else:
#         return False
def is_odd(num):
    return num % 2 == 0
print(list(filter(lambda x: x % 2 == 0, range(10))))
info = [
    ['001', 'apple', 1000, 2],
    ['002', 'xiaomi', 10, 2000],
    ['003', 'Oppo', 200, 1900],
    ['004', 'computer', 900, 5000]
]
def sorted_by_count(item):
    return item[2]
print(sorted(info, key=lambda x: x[2]))

def move_zero(item):
    if item == 0:
        return 1
    else:
        return 0

高阶函数_返回值是函数的
# def compare(base, y):
#     return base > y
# print(compare(5,3))
# print(compare(5,20))
# # 闭包: 函数里面嵌套函数;
# def compare1(base):
#     def compare2(y):
#         return base > y
#     return compare2
# compare_base_10 = compare1(10)
# print(compare_base_10(3))
# print(compare_base_10(20))

# 装饰器: 器:函数, 类; 用来装饰函数的东西;
# 产品经理, 开发人员(ATM)
# 母亲节..... 周末.......
# for i in 'hello':
#     print(i)

# 装饰器应用场景: 如果你想在执行函数之前做什么或者执行函数之后做什么, 建议使用装饰器;
def add_info(fun):  # fun = saveMoney
    def wrapper():
        print("周末......")
        print("欢迎ICBC银行ATM........")
        fun()    # saveMoney()
    return wrapper

# python的语法糖
@add_info    # saveMoney= addinfo(saveMoney)
def saveMoney():
    print("存钱.......")
saveMoney()
# @add_info
# def transferMoney():
#     print("转账......")
# def getMoney():

#     print("取钱.......")

高阶函数及装饰器

装饰器模板

import time
import functools
def add_info(fun):
    @functools.wraps(fun)
    def wrapper(*args, **kwargs):
        # 函数执行之前做的操作
        res =  fun(*args, **kwargs)
        # 函数执行之前做的操作
        return res
    return wrapper
# 需求: 编写一装饰器timeit, 用来装饰某函数执行时间的装饰器;
def timeit(fun):  # fun = add
    def wrapper(x,y):
        start_time = time.time()
        fun(x,y)   # hello()
        end_time = time.time()
        print("%s函数运行时间为%s" % (fun.__name__, end_time - start_time))
    return wrapper
@timeit  # hello = timeit(hello)        # hello = wrapper
def hello():
    time.sleep(0.04)
    print("hello")
@timeit   # add = timeit(add)     # add = wrapper
def add(x,y):
    return x+y
hello()  # wrapper()

print(add(1,3))

万能装饰器

import time
import functools
# 需求: 编写一装饰器timeit, 用来装饰某函数执行时间的装饰器;
def timeit(fun):  # fun = world
    # 2. 注意: functools.wraps(fun): 可以保留add, world等函数的函数名, 帮助文档等属性信息;
    @functools.wraps(fun)
    def wrapper(*args, **kwargs):    # kwargs = {'a':1, 'b':2}
        """
        this is wrapper function。。。。
        :param args:
        :param kwargs:
        :return:
        """
        start_time = time.time()
        temp = fun(*args, **kwargs)         # world(a=1, b=2)
        end_time = time.time()
        print("%s函数运行时间为%s" % (fun.__name__, end_time - start_time))
        return temp
    return wrapper
@timeit  # hello = timeit(hello)        # hello = wrapper
def hello():
    time.sleep(0.04)
    print("hello")
@timeit   # add = timeit(add)     # add = wrapper
def add(x,y):
    """
    add(x:int, y:int)->int:
    :param x:
    :param y:
    :return:
    """
    return x+y
# hello()  # wrapper()
print(add(1,3))
print(add.__name__)
print(add.__doc__)
@timeit         # world = timeit(world)   # world =  wrapper
def world(**kwargs):
    """this is **kwargs test"""
    return kwargs
print(world(a=1, b=2))
print(world.__name__)

print(world.__doc__)

高阶函数及装饰器

return原理

def fun():
    print('hello')
    return "world"   # 在执行函数时, 遇到return, 函数就执行结束;return后面的永不执行;
    print('gcc')

print(fun())

高阶函数及装饰器

装饰器第2个模板

import functools
def is_admin(fun):  # fun=add_student
    @functools.wraps(fun)
    def wrapper(*args, **kwargs): # kwargs = {'name':'root'}
        if kwargs.get('name') == 'root':
            temp = fun(*args, **kwargs)
            return temp
        else:
            print("not root/admin user, no permisson add student")
    return wrapper
@is_admin   # add_student = is_admin(add_student)
def add_student(name):
    print("添加学生信息.....")
add_student(name='root')