【问题标题】:Iterating through user input and a list遍历用户输入和列表
【发布时间】:2016-04-07 15:05:38
【问题描述】:

我需要将用户输入与列表中的一些关键字相匹配。

我已经尝试了几种方法来做到这一点,使用 for、if 和 while。甚至认为枚举是最好的,但似乎无法将它放在一起。我需要考虑到用户可能会输入几个单词。最终代码将与其他内容相关,并打开与关键字相关的文件。

示例代码:

shopping = [
    'bananas',
    'apples',
    'chocolate',
    'coffee',
    'bread',
    'eggs',
    'vimto'
    ]

need = input ("please input what you need ")
need = need.lower()
need = need.split()
index = 0
while index < len(shopping):
    for word in need:
        if word == shopping[index]:
            print ("Added to basket")
            index +=1

        if word != shopping[index]:
            index +=1

如果输入与关键字不匹配,我还需要代码来打印响应。目前找到了关键字,但是如果用户在关键字后面输入任何内容,就会出现错误。

【问题讨论】:

    标签: python iteration


    【解决方案1】:

    您不需要这些疯狂的循环。

    只是简单

    if thing in shopping_list:
        # this is good!
    else:
        # do something
    

    总而言之,您的代码将如下所示:

    need = input("Input what you need: ")
    need = [x.strip() for x in need.lower().strip().split()]
    
    for thing in need:
        if thing in shopping_list:
            print("Added this!")
        else:
            print("No, man, you aren't buying this!")
    

    【讨论】:

      【解决方案2】:

      试试这个:

      shopping = [
          'bananas',
          'apples',
          'chocolate',
          'coffee',
          'bread',
          'eggs',
          'vimto'
          ]
      
      need = input ("please input what you need ")
      need = need.lower()
      need = need.split()
      error = False
      for word in need:
          if word in shopping:
              pass
          else:
              error = True
      
      if Error: print ("Not on the list")
      else: print ("Added to basket")
      

      【讨论】:

      • 谢谢,如果我在关键字周围输入几个词,它会为每个词打印出“不在列表中”,很抱歉很痛苦,但你知道如何阻止它,所以它只打印关闭一次,在用户输入迭代结束时?
      • 非常感谢您,这让我过于复杂,无法透过树木看到树林。
      猜你喜欢
      • 1970-01-01
      • 2021-07-07
      • 2020-12-28
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      相关资源
      最近更新 更多