【问题标题】:python function conditional returnpython函数条件返回
【发布时间】:2021-07-10 20:47:30
【问题描述】:

使用条件返回时,如果您尝试从函数返回多个值,则函数的行为与实际返回值有关。

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return z, w if diagnostic else w

print(test_function(3,4)) # output tuple ([],12)

# lets switch order of the return from z,w to w,z

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return w,z if diagnostic else w

print(test_function(3,4)) # output tuple (12,12) 

# lets try retun the diagnostic value itself to see what function things is happening

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return diagnostic if diagnostic else w

print(test_function(3,4)) # returns 12, so diagnostic is retuning false

# rewrite conditional to "if not"
def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return w if not diagnostic else w,z

print(test_function(3,4)) # returns (12, [])

【问题讨论】:

    标签: python


    【解决方案1】:

    问题是运算符优先级:, 的优先级低于... if ... else ...,所以你实际写的就像return z, (w if diagnostic else w),或者在第二个函数中,它就像return w, (z if diagnostic else w)

    这方面的提示是 diagnosticFalse 但您仍然返回一对值。

    对于你想要的行为,你应该写return (z, w) if diagnostic else w。请注意,此处的括号 不需要 使其成为元组 - 无论哪种方式,它都是一个元组 - 括号用于指定优先级。

    【讨论】:

      【解决方案2】:

      如果在条件返回中返回多个值,由于运算符优先级,这些值必须显式返回为元组:

      def test_function(x,y, diagnostic:bool=False):
                  w = x*y
                  z = []
                  if diagnostic: 
                      z = [w,w*2]
                  return (z, w) if diagnostic else w
                
      print(test_function(3,4)) # returns 12
      print(test_function(3,4, diagnostic=False)) # returns (12, [12, 24])
      w, z = test_function(3,4, diagnostic=True)
      print(w) # returns 12
      print(z) # returns [12,24]
      

      【讨论】:

        猜你喜欢
        • 2016-06-01
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        • 2014-09-15
        • 2021-10-11
        相关资源
        最近更新 更多