-
Write a decorator for the function, output after the function is executed
def end1(func): def new_func(*args,**kwargs): func(*args,**kwargs) print('after') return new_func @end1 def sums(x,y): print('执行结束') sums(1,2)
-
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) if type(result) in (int,float,bool,complex): return result+100 return result return new_func @ add_100 def sums(x,y): return x+y result1=sums(1,2) print(result1)
-
Writing a decorator @tag requires the following functions:
def tag(func): def new_func(*args, **kwargs): result = f'<p>{func(*args, **kwargs)}</p>' return result return new_func @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] result=max([i if i >0 else -i for i in nums]) print(result)
-
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, '女'] def func1(x,y): return x,y result=dict((map(func1,A,B))) print(result)
-
It is known that three lists respectively represent the names, subjects and class numbers of 5 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'] result2 = dict(map(lambda x, y, z: (x,f'{z}{y}'), names, nums, subjects)) print(result2)
-
There is already 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 = ['你好', 20, '30', 5, 6.89, 'hello'] # 列表推导式 result = reduce(lambda x, y: x + y, [i for i in message if type(i) in (int, float)]) print(result) result2 = reduce(lambda x, y: x+y if type(y) in (int,float) else x+0, message,0) print(result2)
Functions and decorator jobs
Guess you like
Origin blog.csdn.net/weixin_44628421/article/details/109065321
Recommended
Ranking