day11-高阶函数作业

  1. 为函数写一个装饰器,在函数执行之后输出 after
def print_end(f):
    def new_f(*args, **kwargs):
        result = f(*args, **kwargs)
        print('after')
        return result
    return new_f

@print_end
def func1():
    print('函数')
    return

func1()
# 函数
# after
  1. 为函数写一个装饰器,把函数的返回值 乘2再返回值
def take2(f):
    def new_f1(*args, **kwargs):
        result = f(*args, **kwargs)
        if type(result) in (int,float,list,str,tuple):
            return result * 2
        return result
    return new_f1

@take2
def func2():
    return 100

print(func2())
  1. 写一个装饰器@tag要求满足如下功能:
def tag(f):
    def new_f1(*args, **kwargs):
        result = f(*args, **kwargs)
        return f'<p>{result}</p>'
    return new_f1

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

@tag
def render2():
    return 'abc'

print(render('Hello'))   # 打印出: <p>Hello</p>
print(render2())     # 打印出: <p>abc</p>
  1. 求列表 nums 中绝对值最大的元素

    # 例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234
    
    nums = [-23, 100, 89, -56, -234, 123]
    r1 = max(nums, key=lambda x: abs(x))
    print(r1)
    
  2. 已经两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value

    A = ['name', 'age', 'sex']
    B = ['张三', 18, '女']
    
    dict1 = map(lambda x, y: (x, y), A, B)
    print(dict(dict1))# {'name': '张三', 'age': 18, 'sex': '女'}
    
  3. 已经三个列表分别表示5个学生的姓名、学科和班号,使用map将这个三个列表拼成一个表示每个学生班级信息的的字典

    names = ['小明', '小花', '小红', '老王']
    nums = ['1906', '1807', '2001', '2004']
    subjects = ['python', 'h5', 'java', 'python']
    dict1 = map(lambda x, y, z: (x, y + z), names, subjects, nums)
    print(dict(dict1))
    
    # {'小明': 'python1906', '小花': 'h51807', '小红': 'java2001', '老王': 'python2004'}
    
  4. 已经一个列表message, 使用reduce计算列表中所有数字的和(用采用列表推导式和不采用列表推导式两种方法做)

    from functools import reduce
    message = ['你好', 20, '30', 5, 6.89, 'hello']
    r1 = reduce(lambda x, y: x + (y if type(y) in [int, float] else 0), message, 0)
    

print(r1) # 31.89

message = [‘你好’, 20, ‘30’, 5, 6.89, ‘hello’]
r2 = sum([x for x in message if type(x) in [int, float]])
print(r2)




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值