【问题标题】:How to test if a user inputted string is in a list?如何测试用户输入的字符串是否在列表中?
【发布时间】:2019-07-27 13:57:13
【问题描述】:

我是 Python 新手,我正在尝试制作一个脚本,让用户选择打开 Windows 命令提示符之类的程序。由于 Windows 命令提示符也使用“cmd”打开,因此我希望用户能够同时键入两者并获得相同的结果。

我知道我可以将它放在多个 elif 语句中,但我想知道我是否可以将两个(或更多)放在一个列表中并让 python 检查用户输入是否在列表中,如果是,打开程序或做任何其他事情

这是我一直在研究的一些测试代码,现在完全被难住了:

userInput = input(">")

userList = []
userList.append(userInput)

commandPrompt = ["cmd", "command prompt"]
testList = ["test1", "test2"]

if userList in commandPrompt:
    print("cmd worked")
elif userInput == testList:
    print("testList worked")
else:
    print("Did not work")

print(userList)

很抱歉,如果以前有人问过这个问题。我在 Google 和 Stack Overflow 上进行了全面检查,但找不到任何与我想要做的文章非常相似的文章,或者无法解释它是否可能。

【问题讨论】:

  • 我无法清楚地理解您想要实现的目标,您介意添加一个带有输入及其各自输出的示例吗?
  • 使用input() 函数与Windows 命令提示符和cmd shell 无关——所以你的问题在现在看来毫无意义。请edit它并尝试澄清您要做什么。

标签: python windows python-2.7 list


【解决方案1】:

假设我理解正确,您正在检查userList 是否在commandPrompt 中。但是commandPrompt 从不包含列表,所以这永远不会满足。

if userInput in commandPrompt: 感觉这可能是您需要的。您不需要将用户的输入放入列表中。

【讨论】:

  • 感谢您的回复,Doe!我知道我错过了那个特定区域的一个小细节,我就是不知道是什么。我的代码完全按照我想要的方式工作。
【解决方案2】:

您可以将代码简化为:

userInput = input(">")

commandPrompt = ["cmd", "command prompt"]
testList = ["test1", "test2"]

if userInput in commandPrompt:
    print("cmd worked")
elif userInput in testList:
    print("testList worked")
else:
    print("Did not work")

这将按照您想要的方式工作。你实际上不需要userList 来做任何事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2022-06-17
    相关资源
    最近更新 更多