How to get a single output from a function with multiple outputs?

前端 未结 3 1900
暖寄归人
暖寄归人 2021-01-15 15:40

I have the following simple function:

def divide(x, y):
    quotient = x/y
    remainder = x % y
    return quotient, remainder  

x = divide(22, 7)
<         


        
相关标签:
3条回答
  • 2021-01-15 16:17

    You are essentially returning a tuple, which is an iterable we can index, so in the example above:

    print x[0] would return the quotient and

    print x[1] would return the remainder

    0 讨论(0)
  • 2021-01-15 16:28

    You have two broad options, either:

    1. Modify the function to return either or both as appropriate, for example:

      def divide(x, y, output=(True, True)):
          quot, rem = x // y, x % y
          if all(output):
              return quot, rem
          elif output[0]:
              return quot
          return rem
      
      quot = divide(x, y, (True, False))
      
    2. Leave the function as it is, but explicitly ignore one or the other of the returned values:

      quot, _ = divide(x, y)  # assign one to _, which means ignore by convention
      rem = divide(x, y)[1]  # select one by index
      

    I would strongly recommend one of the latter formulations; it's much simpler!

    0 讨论(0)
  • 2021-01-15 16:32

    You can either unpack the return values when you call your method:

    x, y = divide(22, 7)
    

    Or you can just grab the first returned value:

    x = divide(22, 7)[0]
    
    0 讨论(0)
提交回复
热议问题