我有一个脚本,需要迭代数千个不同但简单的选项。
我可以使用 if...elif 来迭代它们,但我想知道是否有比数千个 elif 更快/更好的选择。例如
if something == 'a':
do_something_a
elif something == 'b':
do_something_b
elif something == 'c':
do_something_c
elif something == 'd':
do_something_d
...
A thousand more elifs
...
else:
do_something_else
我要做的事情通常是运行某种函数。
最佳答案
您可以使用字典来控制多个可能的逻辑路径:
def follow_process_a():
print('following a')
def follow_process_b():
print('following b')
keyword_function_mapper =
{'a' : follow_process_a ,
'b' : follow_process_b,
}
current_keyword = 'a'
run_method = keyword_function_mapper[current_keyword]
run_method()
关于Python 多个 elif 替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52293173/