首页 > 解决方案 > 如何以 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 的方式来做这种事情?

标签: pythonpython-3.x

解决方案


我喜欢为这种场景使用“分支表”的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)()

推荐阅读