-
为函数写一个装饰器,在函数执行之后输出 after
def after_tag(func): def test(*args, **kwargs): result = func(*args, **kwargs) print('after') return result return test @after_tag def func1(): print('hello') func1()
-
为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def add_100(func): def test(*args, **kwargs): result = func(*args, **kwargs) + 100 # print(result) return result return test @add_100 def func2(x, y): n = x + y return n # func2(1, 2) print(func2(1, 2))
-
写一个装饰器@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(func):
def test(*args, **kwargs):
result = '<p>' + func(*args, **kwargs) + '<p>'
return result
return test
@tag
def render(text):
# 执行其他操作
return text
@tag
def render2():
return 'abc'
print(render('Hello'))
print(render2())
-
求列表 nums 中绝对值最大的元素
例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234
nums = [-23, 100, 89, -56, -234, 123] def func3(sequence): max_num = sequence[0] lens = len(sequence) for i in range(lens): if sequence[i] < 0 and -sequence[i] >= max_num: max_num = -sequence[i] index = i elif sequence[i] >= 0 and sequence[i] >= max_num: max_num = sequence[i] index = i else: pass print(sequence[index]) func3(nums)
-
已知两个列表A和B,用map函数创建一个字典,A中的元素是key,B中的元素是value
A = ['name', 'age', 'sex'] B = ['张三', 18, '女'] 新字典: {'name': '张三', 'age': 18, 'sex': '女'}
A = ['name', 'age', 'sex'] B = ['张三', 18, '女'] def func4(item1, item2): new_list = [] new_list.append(item1) new_list.append(item2) return new_list print(dict(map(func4, A, B)))
-
已知三个列表分别表示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'] def func5(item1, item2, item3): new_list = [] new_list.append(item1) new_list.append(item3 + item2) return new_list print(dict(map(func5, names, nums, subjects)))
-
已知一个列表message, 使用reduce计算列表中所有数字的和(用采用列表推导式和不采用列表推导式两种方法做)
message = ['你好', 20, '30', 5, 6.89, 'hello'] 结果:31.89
from functools import reduce message = ['你好', 20, '30', 5, 6.89, 'hello'] print(reduce(lambda x, y: x + y, [i for i in message if type(i) == int or type(i) == float])) # list1 = [i for i in message if type(i) == int or type(i) == float] # print(list1) def func6(message = ['你好', 20, '30', 5, 6.89, 'hello']): new_list = [] for i in message: if type(i) == int or type(i) == float: new_list.append(i) return new_list print(reduce(lambda x, y: x + y, func6()))