-
Write a decorator for the function, output after the function is executed
def end_after(func): def new_func(*args, **kwargs): result = func(*args, **kwargs) print('after') return result return new_func
-
Write a decorator for the function, set the return value of the function +100 and then return.
def add_100(func): def new_func(*args, **kwargs): result = func(*args, **kwargs) result += 100 print(result) return result return new_func
-
Writing a decorator @tag requires the following functions:
def tag(func):
def new_func(*args, **kwargs):
result = func(*args, **kwargs)
result = '<p>' + str(result) + '</p>'
return result
return new_func
@tag
def render(text):
# 执行其他操作
_ = text
return text
@tag
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
@tag
def render(text):
# 执行其他操作
return text
@tag
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
-
Find the element with the largest absolute value in the list nums
例如:nums = [-23, 100, 89, -56, -234, 123], 最大值是:-234 nums = [-23, 100, 89, -56, -234, 123] print(max(nums, key=lambda item: item if item >= 0 else -item))
-
There are two lists A and B. Use the map function to create a dictionary. The element in A is the key and the element in B is the value.
A = ['name', 'age', 'sex'] B = ['张三', 18, '女'] 新字典: { 'name': '张三', 'age': 18, 'sex': '女'} A = ['name', 'age', 'sex'] B = ['张三', 18, '女'] new_dict = dict(map(lambda item1, item2: (item1, item2), A, B)) print(new_dict)
-
It is known that three lists respectively represent the names, subjects and class numbers of 4 students. Use map to compose these three lists into a dictionary representing the class information of each student
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'] information = dict(map(lambda x, y, z: (x, (z+y)), names, nums, subjects)) print(information)
-
Given a list message, use reduce to calculate the sum of all numbers in the list (using the list comprehension and the non-list comprehension method to do it)
message = ['你好', 20, '30', 5, 6.89, 'hello'] 结果:31.89 # 列表推导式方法: from functools import reduce message_new = [item for item in message if type(item) in (int, float)] print(reduce(lambda x, y: x+y, message_new, 0)) # 非列表推导式方法: message = ['你好', 20, '30', 5, 6.89, 'hello'] message_new = [] for item in message: if type(item) in (int, float): message_new.append(item) print(sum(message_new)) # 其他方法: from functools import reduce print(reduce(lambda x, y: x+(y if type(y) in (int, float) else 0), message, 0))