【问题标题】:Fast way to read possibilities of user input in python在 python 中读取用户输入可能性的快速方法
【发布时间】:2021-03-24 13:32:55
【问题描述】:

假设我必须阅读用户所说的内容,而我的程序会按照他们所说的去做。 像这样的:

userinstructions = input('What action would you like me to do?')

if userinstructions == 'walk':
    walk()

elif userinstructions == 'sleep':
    sleep()

elif userinstructions == 'eat':
    eat()

elif userinstructions == 'talk':
    talk()

现在,假设有数百种可能性,就像在现实生活中一样。我不想为可能数百个语句做 if 语句。有没有办法让它更快并且代码更少?就像可能是一个循环或其他东西。我玩了一会儿,但我什么也想不出来。

【问题讨论】:

标签: python python-3.x if-statement input


【解决方案1】:

您可以定义一个将字符串映射到函数的字典:

actions = {
     'walk': walk,
     'eat': eat,
}

userinstructions = input('What action would you like me to do?')

if userinstructions in actions:
    actions[userinstructions]()
else:
    print('Invalid action')

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2017-07-20
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多