"""
_author_:殷睿
"""
# 1. 为函数写一个装饰器,在函数执行之后输出 after
def end_print(func):
def new_func(*args, **kwargs):
result = func(*args, **kwargs)
print('after')
return result
return new_func
@end_print
def func(x, y):
print(x + y)
func(10, 20)
# 2. 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def add_100(func1):
def new_func(*args, **kwargs):
result = func1(*args, **kwargs)
if type(result) in (int, float, bool, complex):
return result + 100
return result
return new_func
@add_100
def sum1(x, y):
print(x + y)
return x + y
sum1(100, 200)
# 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(func2):
def new_func2(*args, **kwargs):
result = func2(*args, **kwargs)
result = f'<p>{result}</p>'
return result
return new_func2
@tag
def render(text):
return text
@tag
def render2():
return 'abc'
print(render2())
print(render('Hello'))
# list(result).insert(0, '<p>')
# 4.求列表 nums 中绝对值最大的元素
"""
例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234
"""
nums = [-23, 100, 895, -56, -234, 123]
result = max(nums, key=lambda item: item if item > 0 else -item)
# 简单方法
result2 = max(nums, key=lambda item: abs(item))
print(result2)
# 5. 已经两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value
"""
A = ['name', 'age', 'sex']
B = ['张三', 18, '女']
新字典: {'name': '张三', 'age': 18, 'sex': '女'}
"""
A = ['name', 'age', 'sex']
B = ['张三', 18, '女']
result = dict(map(lambda item1, item2: (item1, item2), A, B))
print(result)
# 6. 已经三个列表分别表示5个学生的姓名、学科和班号,使用map将这个三个列表拼成一个表示每个学生班级信息的的字典
"""
names = ['小明', '小花', '小红', '老王']
nums = ['1906', '1807', '2001', '2004']
subjects = ['python', 'h5', 'java', 'python']
结果:{'小明': 'python1906', '小花': 'h51807', '小红': 'java2001', '老王': 'python2004'}
"""
names = ['小明', '小花', '小红', '老王']
nums = ['1906', '1807', '2001', '2004']
subjects = ['python', 'h5', 'java', 'python']
subjects_nums = []
for x in range(0, len(nums)):
subjects_nums.append(subjects[x] + nums[x])
result = dict(map(lambda item1, item2: (item1, item2), names, subjects_nums))
print(result)
# 简单方法
result = dict(map(lambda a, b, c: (a, f'{c}{b}'), names, nums, subjects))
# 7. 已经一个列表message, 使用reduce计算列表中所有数字的和(用采用列表推导式和不采用列表推导式两种方法做)
"""
message = ['你好', 20, '30', 5, 6.89, 'hello']
结果:31.89
"""
from functools import reduce
message = ['你好', 20, '30', 5, 6.89, 'hello']
def int_float(list1):
y = 0
for x in list1:
if type(x) == int or type(x) == float:
y += x
return y
# result = reduce(int_float, message, 0)
# print(int_float(message))
result = reduce(lambda item1, item2: item1 + item2,
(x for x in message if type(x) == int or type(x) == float), 0)
print(result)
result = reduce(lambda x, y: x + (y if type(y) in [int, float] else 0), message, 0)
高阶函数装饰器作业
最新推荐文章于 2022-01-15 13:46:29 发布
本文介绍了Python编程中装饰器的使用,包括在函数执行后添加额外操作和修改函数返回值的装饰器实现。同时,展示了如何通过装饰器在HTML中包装文本输出,以及如何利用装饰器和映射函数创建字典。此外,还涵盖了列表和字符串处理,如求列表中绝对值最大值和使用reduce函数计算数字之和。最后,演示了如何将多个列表组合成字典,用于表示学生信息。
摘要由CSDN通过智能技术生成