python - 如何以 Pythonic 方式为每个不同的输入设置规则?
问题描述
更改对查询的每个可能响应的操作过程的最佳方法是什么?
例如,目前如果我想这样做,我会这样做:
list_of_answers = ["One answer", "Another", "One more", "Yet another"]
print(list_of_answers)
user_input = input("Choose from the above list")
if user_input = "One answer":
#do this
elif user_input = "Another":
#do that
...
#etc, etc
这对于提供的示例来说很好,但如果我说 20 种可能的选择,我不想要一大块if this... that, elif this... that
.
我想知道是否有一种 Pythonic 的方式来做这种事情?
解决方案
我喜欢为这种场景使用“分支表”的pythonic实现。它看起来很干净,您可以轻松添加选项。
HANDLERS = {"One answer": handle_one_answer, "Another": handle_second_answer}
def handle_one_answer():
pass
def handle_second_answer():
pass
def default_handler():
pass
def main():
print(HANDLERS.keys())
user_input = input("Choose from the above list")
HANDLERS.get(user_input, default_handler)()
推荐阅读
- vector - 在 PySpark 中过滤密集向量
- kotlin - Kotlin:直到n的素数列表
- java - 查询问题——在JDBC中插入(双引号、单引号)
- sendgrid - Sendgrid 图像 URL 未显示,但它在那里
- javascript - 通过javascript将多个输入附加到表中
- accessibility-insights - Accessibility Insights 自动化测试不同于 Ax
- eclipse - 有没有办法为 Eclipse 插件设置最大支持的 Eclipse 版本?
- c++ - C ++如何打印向量的索引?
- javascript - 农业网格中的可编辑组单元格
- javascript - 类型检查在常规 JS-File 中的 VSCode 中引发错误