我想到一个脚本,该脚本需要一个if语句,并带有大约30多个elifs。 所以我正在尝试一种字典方法:
def a():
print('a')
return 'A is the number'
def b():
print('b')
return 'vvb is the number'
def c():
print('c')
return 'c is the number'
name = input('type it in: ')
list = {'a': a(), 'b': b(), 'c': c()}
if name in list:
this = list[name]
print(this)
else:
print('name not in list')
理论上,当我输入'a'
时,它应该返回"A is the number"
但这就是我得到的:
type it in: a
a
b
c
A is the number
因此,很明显,列表执行了所有功能,如果我有30多个大型功能,它将大大降低速度。有没有办法只执行被调用的功能?
或者也许有更好的方法可以做到这一点? 流程结束,退出代码为0
答案 0 :(得分:3)
list = {'a': a(), 'b': b(), 'c': c()}
不要那样做。您想要的是这样:
d = {'a': a, 'b': b, 'c': c}
然后,您要调用该函数
一旦您知道name
是什么:
this = d[name]()
此外,请不要使用list
或dir
之类的标识符
已经定义为builtin的文件。
更好地称其为d
来作为字典。
list()
函数非常有用,
您可能很快会发现需要调用它,
甚至在相同的功能内。
当事物不是列表时称其为“列表”
不会帮助您正确地对此进行推理。
通常是name_to_fn[]
开头的标识符
适用于字典映射,
在这种情况下说明
它从名称映射到功能。
答案 1 :(得分:1)
一种选择是从list
键中删除函数调用(还将list
重命名为内置python关键字以外的其他名称,例如mylist
)。
然后在print()
函数中调用结果函数:
mylist = {'a': a, 'b': b, 'c': c}
if name in mylist.keys():
this = mylist[name]
print(this())
结果:
type it in: a
a
A is the number