【问题标题】:Python: Skip a block of code (calculation) when certain condition is met without using "if" statementsPython:在不使用“if”语句的情况下满足特定条件时跳过代码块(计算)
【发布时间】:2017-02-20 05:45:32
【问题描述】:

我有一小段代码,我正试图以更好的方式编写它,因为它有一堆“if”语句。这是一些大项目的小代码。问题是这样的:当代码运行时,函数“f”、“g”或/和“k”可以返回 None 或数值数据。每当返回 None 值时,必须跳过其余的计算,因为无法完成数学运算(发生在这些函数中)。我尝试使用 TRY/CATCH 方法重写代码,但无法使其工作。我试图避免“if”语句并重写简洁的方式。我很感激帮助。


def f(output):
    #some code which computes output which be None or numerical
    return [output*1,2]
def g(Y):
    #some code which computes Y which be None or numerical
    return Y*3
def k(output):
  #some code which computes output which be None or numerical
  return output*4
def foutput():
  #some code which computes "value" which be None or numerical 
  value=2.0
  return 1.0*value


#####START
#some code
output=foutput()

if output is not None:
    print 'S1'
    [output,A]=f(output)
    if output is not None:
        print 'S2'
        [a,b,c,Y]=[1,2,3,k(output)]
        if Y is not None:
            print 'S3'
            A=g(Y)
        else:
            [Q,A,output]=[None,None,None]
    else:
        [Q,A,output]=[None,None,None]
else:
    [Q,A,output]=[None,None,None]

【问题讨论】:

  • try/except 方法有什么问题? (我假设你的意思是你有 f、g 和 k 抛出异常而不是返回 None,并将 [Q,A,output]=[None,None,None] 放在 except 块中?)
  • 您可以“标准化”函数签名,然后通过简单的中间检查让它们一个接一个地执行,但在您的情况下,简单的 try/except 应该绰绰有余 - 只需让您的函数引发特定异常,然后让您的代码线性执行并用 try/except 块包围它以捕获“非标准”返回(例如,如果任何函数返回 None

标签: python if-statement try-catch


【解决方案1】:

确定每个步骤中将引发的错误,然后将这些异常添加到try..except。在这个玩具示例中,它们都是TypeError,但我将添加ValueError 作为演示:

def f(output):
    #some code which computes output which be None or numerical
    return [output*1,2]
def g(Y):
    #some code which computes Y which be None or numerical
    return Y*3
def k(output):
  #some code which computes output which be None or numerical
  return output*4
def foutput():
  #some code which computes "value" which be None or numerical 
  value=2.0
  return 1.0*value


output=foutput()

try:
    print 'S1'
    output, A = f(output)
    print 'S2'
    a, b, c, Y = 1, 2, 3, k(output)
    print 'S3'
    A = g(Y)
except (ValueError, TypeError):
    Q = A = output = None
else:
    Q = 'success' # if none of this fails, you might want a default value for Q

【讨论】:

    【解决方案2】:

    我想我有一个解决办法:

    def compute():
        if f() is not None: print 'S1'
        else: return
        if g() is not None: print 'S2'
        else: return
        if k() is not None: print 'S3'
        else: return
    
    compute()
    

    仍有if 语句,但它们不会像原始代码中那样令人困惑地嵌套。

    这使用了这样一个事实,即当您从一个函数中return 时,该函数的其余部分将被跳过并且该函数中的计算结束。

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      相关资源
      最近更新 更多