How can I return two values from a function in Python?

前端 未结 8 681
执笔经年
执笔经年 2020-11-22 12:14

I would like to return two values from a function in two separate variables. For example:

def select_choice():
    loop = 1
    row = 0
    while loop == 1:         


        
相关标签:
8条回答
  • 2020-11-22 12:20
    def test():
        r1 = 1
        r2 = 2
        r3 = 3
        return r1, r2, r3
    
    x,y,z = test()
    print x
    print y
    print z
    
    
    > test.py 
    1
    2
    3
    
    0 讨论(0)
  • 2020-11-22 12:22

    And this is an alternative.If you are returning as list then it is simple to get the values.

    def select_choice():
        ...
        return [i, card]
    
    values = select_choice()
    
    print values[0]
    print values[1]
    
    0 讨论(0)
  • 2020-11-22 12:24
    def test():
        ....
        return r1, r2, r3, ....
    
    >> ret_val = test()
    >> print ret_val
    (r1, r2, r3, ....)
    

    now you can do everything you like with your tuple.

    0 讨论(0)
  • 2020-11-22 12:37

    You can return more than one value using list also. Check the code below

    def newFn():    #your function
      result = []    #defining blank list which is to be return
      r1 = 'return1'    #first value
      r2 = 'return2'    #second value
      result.append(r1)    #adding first value in list
      result.append(r2)    #adding second value in list
      return result    #returning your list
    
    ret_val1 = newFn()[1]    #you can get any desired result from it
    print ret_val1    #print/manipulate your your result
    
    0 讨论(0)
  • 2020-11-22 12:38

    You cannot return two values, but you can return a tuple or a list and unpack it after the call:

    def select_choice():
        ...
        return i, card  # or [i, card]
    
    my_i, my_card = select_choice()
    

    On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().

    If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:

    data, errors = MySchema.loads(request.json())
    if errors:
        ...
    

    or

    result = MySchema.loads(request.json())
    if result.errors:
        ...
    else:
        # use `result.data`
    

    In other cases you may return a dict from your function:

    def select_choice():
        ...
        return {'i': i, 'card': card, 'other_field': other_field, ...}
    

    But you might want consider to return an instance of a utility class, which wraps your data:

    class ChoiceData():
        def __init__(self, i, card, other_field, ...):
            # you can put here some validation logic
            self.i = i
            self.card = card
            self.other_field = other_field
            ...
    
    def select_choice():
        ...
        return ChoiceData(i, card, other_field, ...)
    
    choice_data = select_choice()
    print(choice_data.i, choice_data.card)
    
    0 讨论(0)
  • 2020-11-22 12:39

    I would like to return two values from a function in two separate variables.

    What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

    Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

    When i tried to to use return i, card, it returns a tuple and this is not what i want.

    Actually, it's exactly what you want. All you have to do is take the tuple apart again.

    And i want to be able to use these values separately.

    So just grab the values out of the tuple.

    The easiest way to do this is by unpacking:

    a, b = select_choice()
    
    0 讨论(0)
提交回复
热议问题