合并具有两种不同条件的相同操作的代码

时间:2017-06-27 00:00:43

标签: if-statement merge

我有一个问题。我试图整理一些编码。 我有这部分代码

        if (self.type == self.BETAECM):
        for line in contentInfo:
            if line.startswith("caid:"):
                caid = self.readEcmInfo(line)
                if "x" in caid:
                    idx = caid.index("x")
                    caid = caid[(idx + 1):]
                    caid = caid[:4]
                    caid = caid.upper()
                    if (caid >= "1700") and (caid <= "17FF"):
                        return True
            elif line.startswith("====="):
                caid = self.readCaid(line)                        
                if "x" in caid:
                    idx = caid.index("x")
                    caid = caid[(idx + 1):]
                    caid = caid[:4]
                    caid = caid.upper()
                    if (caid >= "1700") and (caid <= "17FF"):
                        return True
        return False

正如您所看到的,使用相同的操作处理两个不同的条件 我想整理一切,以便代码的相同部分(以&#34; x&#34; caid开头)只写一次。这可能吗? 提前谢谢!

3 个答案:

答案 0 :(得分:2)

我不懂这种语言,但我会捅它。

for line in contentInfo:
  caid = "nothing"
  if line.startswith("caid:"):
    caid = self.readEcmInfo(line)
  elif line.startswith("====="):
    caid = self.readCaid(line)                        
  if "x" in caid:
    idx = caid.index("x")
    caid = caid[(idx + 1):]
    caid = caid[:4]
    caid = caid.upper()
    if (caid >= "1700") and (caid <= "17FF"):
      return True

答案 1 :(得分:0)

您需要使用OR运算符连接它们。换句话说,为了优化你的代码,你应该是一个条件或另一个条件。

if line.startswith("caid:") || line.startswith("====="):

答案 2 :(得分:0)

非常感谢你! 我缺少的是最后一个if语句(如果&#34; x&#34;在caid :)必须与前一个相同。它现在有效!

所以,如果我想合并另一个例子:

def readEcmInfo(self, line):
    if ":" in line:
        idx = line.index(":")
        line = line[(idx + 1):]
        line = line.replace("\n", "")
        while line.startswith(" "):
            line = line[1:]
        while line.endswith(" "):
            line = line[:-1]
        return line
    else:
        return ""
    elif "CaID" in line:
        idx = line.index("D")
        line = line[(idx + 1):]
        line = line.replace("\n", "")
        while line.startswith(" "):
            line = line[1:]
        while line.endswith(" "):
            line = line[:-1]
        return line
    else:
        return ""

应该这样吗?

def readEcmInfo(self, line):
    if ":" in line:
        idx = line.index(":")
        line = line[(idx + 1):]
        line = line.replace("\n", "")
    elif "CaID" in line:
        idx = line.index("D")
        line = line[(idx + 1):]
        line = line.replace("\n", "")
    while line.startswith(" "):
        line = line[1:]
    while line.endswith(" "):
        line = line[:-1]
        return line
    else:
        return ""