gpt4 book ai didi

python - 如何使用字典执行多个函数?

转载 作者:行者123 更新时间:2023-11-28 20:57:02 25 4
gpt4 key购买 nike

我在这段代码中有一个字典 switcher:

def a():
print("A")

def b():
print('B')


def switch(mode):
switcher = {
'a': a,
'b': b,
'ab': (a, b)
}
switcher[mode]()

switch('a')

如果我使用 switch('a') 我会得到输出:

A

到目前为止,使用 switch('ab') 返回错误:

TypeError: 'tuple' object is not callable.

如何使用 switch('ab') 执行 ab

最佳答案

通过为可迭代对象引入for循环

def a():
print("A")

def b():
print('B')


def switch(mode):
switcher = {
'a': a,
'b': b,
'ab': (a, b)
}
for i in mode:
switcher[i]()

switch('ab')

输出

A
B

关于python - 如何使用字典执行多个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com