-
関数のデコレータを記述し、関数の実行後に出力します
def end_after(func): def new_func(*args, **kwargs): result = func(*args, **kwargs) print('after') return result return new_func
-
関数のデコレータを記述し、関数の戻り値を+100に設定してから、戻ります。
def add_100(func): def new_func(*args, **kwargs): result = func(*args, **kwargs) result += 100 print(result) return result return new_func
-
デコレータ@tagを作成するには、次の関数が必要です。
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>
-
リスト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))
-
AとBの2つのリストがあります。map関数を使用して辞書を作成します。Aの要素がキーで、Bの要素が値です。
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)
-
3つのリストは、それぞれ4人の学生の名前、科目、クラス番号を表すことが知られています。マップを使用して、これら3つのリストを各学生のクラス情報を表す辞書に構成します。
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)
-
リストメッセージが与えられたら、reduceを使用して、リスト内のすべての数値の合計を計算します(リスト内包表記法と非リスト内包表記法を使用して計算します)
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))