【问题标题】:Given two "if" statements, execute some code if none of them is executed给定两个“if”语句,如果其中没有一个被执行,则执行一些代码
【发布时间】:2018-05-11 13:14:38
【问题描述】:

嘿,我不知道如何编程这个星座:

string = " "
if "abc" in string:
    print ("abc is in string")
if "def" in string:
    print ("def is in string")
else:
    print ("abc and def are not contained in string")

只有当 2 个条件不成立时,它才应该转到“else”。但是如果两个子字符串都包含在字符串中;它应该同时打印。

【问题讨论】:

    标签: python if-statement


    【解决方案1】:

    您可以简单地为每个条件定义一个布尔值 它使代码保持简单

    abc = "abc" in string
    def_ = "def" in string
    if abc : 
        print("abc in string")
    if def_ : 
        print("def in string")
    if not (abc or def_) : 
        print("neither abc nor def are in this string")
    

    【讨论】:

    • 您必须将def 替换为def_,因为它是关键字。
    【解决方案2】:

    另一种选择是使用仅在之前满足条件时才为真的变量。这个变量(我们称之为found)默认为false:

    found = False
    

    但是,在每个if 语句中,我们将其设置为True

    if "abc" in string:
        print ("abc is in string")
        found = True
    
    if "def" in string:
        print ("def is in string")
        found = True
    

    现在我们只需要检查变量。如果满足任何条件,则为真:

    if not found:
        print ("abc and def are not contained in string")
    

    这只是解决这个问题的一种选择,但我已经看到这种模式被多次使用了。当然,如果你觉得更好,你可以选择其他方法。

    【讨论】:

      【解决方案3】:

      我想展示另一种方法。优点是它将代码分为两个逻辑步骤。然而,在像这个示例问题这样简单的情况下,可能不值得付出额外的努力。

      这两个步骤是: 1. 获取所有部分结果; 2. 全部处理

      DEFAULT = ["abc and def are not contained in string"]
      string = "..."
      
      msglist = []
      if "abc" in string:
          msglist.append("abc is in string")
      if "def" in string:
          msglist.append("def is in string")
      # more tests could be added here
      
      msglist = msglist or DEFAULT
      for msg in msglist:
          print(msg)
          # more processing could be added here
      

      【讨论】:

        【解决方案4】:

        循环遍历它们怎么样?这是完全通用的,可以用于检查您可能需要的任意数量的字符串。

        string = " "
        strs = ("abc", "def")
        if any(s in string for s in strs):
            for s in strs:
                if s in string:
                    print ("{} is in string".format(s))
        else:
            print (" and ".join(strs) + " are not contained in string")
        

        你有一个live example

        【讨论】:

          【解决方案5】:

          您可以将字典用作 switch case 语句的等价物(尽管它会稍微改变输出):

          msg = {
              (True, True): "abc and def in string",
              (True, False): "abc in string",
              (False, True): "def in string",
              (False, False): "neither abc nor def in string"
          }[("abc" in string, "def" in string)]
          
          print(msg)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-11-09
            • 1970-01-01
            • 2018-10-29
            • 1970-01-01
            • 2019-11-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多