1.为函数写一个装饰器,在函数执行之后输出 after
def print_after(fn):
def new_fn(*args, **kwargs):
result = fn(*args, **kwargs)
print('after')
return result
return new_fn
2.为函数写一个装饰器,把函数的返回值 乘2再返回值
def ride_two(fn):
def new_fn(*args, **kwargs):
result = fn(*args, **kwargs)
result *= 2
return result
return new_fn
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 double_p(fn):
def new_fn(*args, **kwargs):
result = fn(*args, **kwargs)
result = '<p>' + str(result) + '</p>'
return result
return new_fn
4.求列表 nums 中绝对值最大的元素
例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234
result = max(序列, key=匿名函数) 匿名函数 = lambda 参数列表: 返回值
result = max(nums, key=lambda item: abs(item))
5.已知两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value
A = ['name', 'age', 'sex']
B = ['张三', 18, '女']
新字典: {'name': '张三', 'age': 18, 'sex': '女'}
map(函数,序列1, 序列2)
result = dict(map(lambda item1, item2: (item1, item2), A, B))
6.已经三个列表分别表示5个学生的姓名、学科和班号,使用map将这个三个列表拼成一个表示每个学生班级信息的的字典
names = ['小明', '小花', '小红', '老王']
nums = ['1906', '1807', '2001', '2004']
subjects = ['python', 'h5', 'java', 'python']
结果:{'小明': 'python1906', '小花': 'h51807', '小红': 'java2001', '老王': 'python2004'}
map(函数,序列1,序列2,序列3)
result = dict(map(lambda item1, item2, item3: (item1, item2+item3), names, nums, subjects))
7.已经一个列表message, 使用reduce计算列表中所有数字的和(用采用列表推导式和不采用列表推导式两种方法做)
message = ['你好', 20, '30', 5, 6.89, 'hello']
结果:31.89
from functools import reduce
reduce(函数,序列1,初始值)
result = reduce(lambda x, item: x + (item if type(item) in [int, float] else 0), message, 0)