day12func_decorator

一、函数的本质

  1. 函数的本质

    • python中定义函数其实就是在定义一个类型是function的变量,函数名就是变量名,变量能做的函数都可以做

二、常用的实参高阶函数

  1. max、min、sorted
  • max(序列,key=函数)、sorted(序列,key=函数)、列表.sort(key=函数)

    • 函数的要求:

      a.有且只有一个参数,这个参数指向的数是前面序列中的每一个元素

      b.需要一个返回值,返回值决定求最大值的时候的比较对象

    # 求列表nums中个位数最大的元素: 19
    nums = [28, 87, 65, 19, 25]
    result=max(nums,key=lambda item:item%10)
    nums = [28, 607, -650, 19, -85]
    result=max(nums,key=lambda item:item if item>0 else -item)
    # 求列表nums中十位数最大的元素:
    nums = [28, 607, 65, 19, 85]
    result = max(nums,key=lambda item:item//10%10)
    # 练习:求列表中各个位上和最大的元素
    nums = [28, 607, 65, 19, 88]
    result = max(nums,key=lambda item:sum([int(i) for i in str(item)]))
    # 练习:用min获取students中年龄最小的学生
    students = [
        {'name': '小明', 'age': 18, 'score': 98, 'tel': '187283822'},
        {'name': '小红', 'age': 30, 'score': 99, 'tel': '187283827'},
        {'name': 'Tom', 'age': 25, 'score': 87, 'tel': '187283821'},
        {'name': 'Bob', 'age': 19, 'score': 65, 'tel': '187283820'}
    ]
    result = min(students,key=lambda stu:stu['age'])
    # 将列表中的元素按照个位数的大小从小到大排序
    nums = [28, 87, 65, 19, 25]
    result=sorted(nums,key=lambda item:item%10)
    
  1. map函数

    map(函数,序列1,序列2,…)

  • 函数的要求

    • a.有且只有N个参数,这个参数指向的是后面N个序列的每个元素
    • b。需要一个返回值,描述新序列中的元素和原序列中元素的关系
    nums = [28, 89, 34, 78, 21]  #[8, 9, 4, 8, 1]
    result=map(lambda item:item%10,nums)
    #------------------------------
    nums1 = [10, 20, 30, 40]
    nums2 = [100, 200, 300, 400]
    # [110, 220, 330, 440]
    result = map(lambda item1, item2: item1 + item2, nums1, nums2)
    print(list(result))   # [110, 220, 330, 440]
    #---------------------------
    values = ['小明', 18, 90]
    keys = ['name', 'age', 'score']
    # {'name': '小明', 'age': 18, 'score': 90}
    result = map(lambda item1, item2: (item1, item2), keys, values)
    print(dict(result))   # {'name': '小明', 'age': 18, 'score': 90}
    
  1. reduce函数 – 将序列中所有元素通过指定的方式合并成一个数据

    reduce(函数,序列,初始值)

    函数的要求:

    a.有且只有两个参数:第一个第一次指向初始值,从第二次开始指向上一次的计算结果,第二个参数指向序列中的每个元素

    b.需要一个返回值,返回值用来描述合并规则

    nums = [20, 34, 45, 10]
    result = reduce(lambda x item :x+item ,nums,0)
    #----------------
    nums = [2, 4, 5, 6, 3]    # 2*4*5*6*3
    result = reduce(lambda x item: x*item,nums,1)
    #----------------
    nums = [23, '45', 10, 2, '30']   # 23+45+10+2+30
    result = reduce(lambda x item :x+int(item),nums,0)
    #-------------
    nums = [23, '45', 10, 2, '30']   # 23+10+2
    result = reduce(lambda x, item: x + (item if type(item) == int else 0), nums, 0)
    
    #--------------
    students = [
        {'name': '小明', 'age': 18, 'score': 98, 'tel': '187283822'},
        {'name': '小红', 'age': 30, 'score': 99, 'tel': '187283827'},
        {'name': 'Tom', 'age': 25, 'score': 87, 'tel': '187283821'},
        {'name': 'Bob', 'age': 19, 'score': 65, 'tel': '187283820'}
    ]
    result = reduce(lambda x, item: x + item['score'], students, 0) / len(students)
    print(result)
    

三、装饰器

  1. 装饰器就是给函数添加功能的、装饰器=实参高阶函数+返回值高阶函数+糖语法
  • 语法:

    def 装饰器名称(需要添加功能的函数):

    ​ def添加过功能的新函数(*args,**kwargs):

    ​ 需要添加功能的函数(*args,**kwargs)

    ​ 添加新功能

    ​ return 原函数返回值(如果装饰器本身的功能和原函数,有关,这个地方就不一定)

    ​ return 添加过功能的新函数

    # 练习:写一个装饰器,将函数的返回值加100。 1  -> 101
    def value_add(f):
        def new_f(*args,**kwargs):
            result = f(*args,**kwargs)
            if type(result)in(int,float,bool,complex):
                return result+100
            return
        return nwe_f
    
    
    @value_add
    def func33(N: int):
        result = reduce(lambda x, item: x * item, range(1, N + 1), 1)
        return result
    
    

作业

1.为函数写一个装饰器,在函数执行之后输出 after

def add_after(func):
    def nwe_f(*args,**kwargs):
        func(*args,**kwargs)
        print('after')
    return nwe_f()

@add_after
def func2():
    print('hello world!')

2.为函数写一个装饰器,把函数的返回值 乘2再返回值

def value_add(f):
    def new_f(*args, **kwargs):
        result = f(*args, **kwargs)
        return result * 2

    return new_f

3.写一个装饰器@tag要求满足如下功能:

@tag
def render(text):
    # 执行其他操作
    return text

@tag
def render2():
    return 'abc'

print(render('Hello'))   # 打印出: <p>Hello</p>
print(render2())     # 打印出: <p>abc</p>
#-------------------
def tag(f):
    def new_f(*args, **kwargs):
        result = f(*args, **kwargs)
        return '<p>'+result+'<p>'

    return new_f

4.求列表 nums 中绝对值最大的元素

nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234
def abs_1(string):
    result = [i if i>0 else -i for i in string]
    index1=result.index(max(result))
    return nums[index1]

5.已经两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value

A = ['name', 'age', 'sex']
B = ['张三', 18, '女']
新字典: {'name': '张三', 'age': 18, 'sex': '女'}
    
result = map(lambda item1, item2: (item1, item2), A, B)
print(dict(result))

6.已经三个列表分别表示4个学生的姓名、学科和班号,使用map将这个三个列表拼成一个表示每个学生班级信息的的字典

names = ['小明', '小花', '小红', '老王']
nums = ['1906', '1807', '2001', '2004']
subjects = ['python', 'h5', 'java', 'python']
结果:{'小明': 'python1906', '小花': 'h51807', '小红': 'java2001', '老王': 'python2004'}
result = map(lambda item1,item2,item3:(item1,item3+item2),names,nums,subjects)
print(dict(result))

7.已经一个列表message, 使用reduce计算列表中所有数字的和(用采用列表推导式和不采用列表推导式两种方法做)

from functools import reduce
message = ['你好', 20, '30', 5, 6.89, 'hello']

result = reduce(lambda x, item: x + (item if type(item) in (int, float) else 0), message, 0)
print(result)

result = reduce(lambda x, item: x + item, [i for i in message if type(i) in (int, float)], 0)
print(result)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值