【问题标题】:Checking input against list elements in Python根据 Python 中的列表元素检查输入
【发布时间】:2016-12-08 02:07:12
【问题描述】:

我正在尝试制作一个简单的程序,它首先检查用户的输入是否与列表匹配,然后检查输入匹配的列表元素并根据输入给出响应。我遇到问题的部分是,想出一种方法来查看输入匹配列表中的哪个元素,以便我可以根据该输入给出特定的响应。我真的很感激能在这个问题上得到任何帮助。

谢谢,新星

这是我目前拥有的代码。在第一个 if 语句下,我想检查列表中的哪些元素与输入匹配。

Y = ["How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
I = str(input("Start Conversation"))

if I in Y:
    print("Working");

elif I not in Y:
    print("I don't Understand");

【问题讨论】:

  • 如果输入匹配列表中的某些内容,为什么不直接使用输入本身?

标签: python list input


【解决方案1】:

可以使用python优秀的list.index函数:

if I in Y:
  print("Working" + str(Y.index(I)));

【讨论】:

  • 非常感谢,这很简单,而且效果很好!
【解决方案2】:

如果你愿意,你可以把它作为一个单线扔进去:

Y = ["How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
I = str(input("Start Conversation"))

print("Working:", I) if I in Y else print("I don't understand")

正如 Thmei 已经指出的,if 匹配 IY,因此您已经知道 I 的内容在列表中并且可以打印。如果您希望在Y 中输出I 的实际索引(如果存在),您可以这样做:

print(Y.index(I)) if I in Y else print("I don't understand")

或者很长的路:

if I in Y:
    print (Y.index(I))
else:
    print ("I don't understand")

【讨论】:

    【解决方案3】:

    由于您已经将I 与列表中的项目进行了匹配,如果I 匹配其中之一,它将与它匹配的项目相同。

    print(I)
    

    【讨论】:

      【解决方案4】:
      for a in Y:
            if I == a:
                  #do something
      

      【讨论】:

        猜你喜欢
        • 2016-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        相关资源
        最近更新 更多