【问题标题】:Pulling from List using If/Else statement - Python使用 If/Else 语句从列表中拉取 - Python
【发布时间】:2016-08-11 13:45:21
【问题描述】:

我想从我的列表中匹配正确的术语。这是我的代码:

stuff = ["cat", "dog", "house", "cat", "mouse"]

for item in stuff:
    if "house" in item:
        print "house good"
    if "cat" in item:
        print "cat good"
    if "dog" in item:
        print "dog good"
    else:
        print "nothing else"

目前的结果是这样的:

cat good
nothing else
dog good
house good
nothing else
cat good
nothing else
nothing else

但我希望结果是这样的:

cat good
dog good
house good 
cat good 
nothing else

由于我的 else 语句,目前脚本一直在拉“没有别的”。但是我不知道如何仅在我的列表中的一个术语与我的 if 语句中的术语不匹配时才使“没有别的”出现。有谁知道我可以做到这一点?

【问题讨论】:

    标签: python list


    【解决方案1】:

    你应该使用elif,像这样:

    for item in stuff:
        if "house" in item:
            print "house good"
        elif "cat" in item:
            print "cat good"
        elif "dog" in item:
            print "dog good"
        else:
            print "nothing else"
    

    否则else 仅适用于最后一个if

    【讨论】:

      【解决方案2】:

      您应该使用elif 使所有条件成为同一语句的一部分。目前 else 只适用于最后一个条件。

      if "house" in item:
          print "house good"
      elif "cat" in item:
          print "cat good"
      elif "dog" in item:
          print "dog good"
      else:
          print "nothing else"
      

      【讨论】:

      • 显然。非常感谢。
      【解决方案3】:

      您必须使用 elif 条件,例如:

      stuff = ["cat", "dog", "house", "cat", "mouse"]
      
      for item in stuff:
          if "house" in item:
              print ("house good")
          elif "cat" in item:
              print ("cat good")
          elif "dog" in item:
              print ("dog good")
          else:
              print ("nothing else")
      

      【讨论】:

        【解决方案4】:

        其他答案建议您应该使用elif 语句来修复您的代码。这是完全合理的。但是,我只想指出,通过对代码进行轻微重构,您可以使其更简单、更具可读性和可扩展性:

        stuff = ["cat", "dog", "house", "cat", "mouse"]
        good_stuff = set(["house", "cat", "dog"])
        
        for item in stuff:
            if item in good_stuff:
                print item + " good"
            else:
                print "nothing else"
        

        任何时候你发现自己使用ifelifelifelif,...通常是因为你有designed your code badly

        请注意,我在这里使用set 进行优化。如果你不知道为什么,那么我建议你看here

        【讨论】:

          【解决方案5】:

          尽量不要使用'in',如果我是你,我会尝试使用'=='。

          但判断它已经在列表中,所以我猜你不需要'for'部分,只需要'if xxx in stuff'

          希望这会有所帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-12-22
            • 2020-07-30
            • 1970-01-01
            • 1970-01-01
            • 2022-07-23
            • 2015-04-27
            • 2020-02-21
            相关资源
            最近更新 更多