问题:如何从Python中的函数返回两个值?

我想在两个单独的变量中从函数返回两个值。例如:

def select_choice():
    loop = 1
    row = 0
    while loop == 1:
        print('''Choose from the following options?:
                 1. Row 1
                 2. Row 2
                 3. Row 3''')

        row = int(input("Which row would you like to move the card from?: "))
        if row == 1:
            i = 2
            card = list_a[-1]
        elif row == 2:
            i = 1
            card = list_b[-1]
        elif row == 3:
            i = 0
            card = list_c[-1]
        return i
        return card

我希望能够分别使用这些值。当我尝试使用时return i, card,它返回a tuple,这不是我想要的。

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:
        print('''Choose from the following options?:
                 1. Row 1
                 2. Row 2
                 3. Row 3''')

        row = int(input("Which row would you like to move the card from?: "))
        if row == 1:
            i = 2
            card = list_a[-1]
        elif row == 2:
            i = 1
            card = list_b[-1]
        elif row == 3:
            i = 0
            card = list_c[-1]
        return i
        return card

And I want to be able to use these values separately. When I tried to use return i, card, it returns a tuple and this is not what I want.


回答 0

您不能返回两个值,但可以返回a tuple或a list并在调用后解压缩它:

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

my_i, my_card = select_choice()

在线return i, card i, card意味着创建一个元组。您也可以使用括号,例如return (i, card),但是元组是用逗号创建的,因此括号不是必需的。但是,您可以使用parens来提高代码的可读性或将元组分成多行。这同样适用于line my_i, my_card = select_choice()

如果要返回两个以上的值,请考虑使用命名的tuple。它将允许函数的调用者按名称访问返回值的字段,这样更易​​于阅读。您仍然可以按索引访问元组的项目。例如,在Schema.loadsMarshmallow框架方法中,返回的UnmarshalResult是a namedtuple。因此,您可以执行以下操作:

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

要么

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

在其他情况下,您可以dict从函数中返回a :

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

但是您可能要考虑返回一个实用程序类的实例,该实例包装您的数据:

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)

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)

回答 1

我想在两个单独的变量中从函数返回两个值。

您希望它在呼叫端看起来像什么?您无法编写,a = select_choice(); b = select_choice()因为那样会调用该函数两次。

值不“在变量中”返回;那不是Python的工作方式。函数返回值(对象)。变量只是给定上下文中值的名称。当您调用函数并在某处分配返回值时,您正在做的就是在调用上下文中为接收到的值命名。该函数不会为您将值“放入变量”中,赋值却会这样做(不必担心变量不是该值的“存储”,而是一个名称)。

当我尝试使用时return i, card,它返回a tuple,这不是我想要的。

实际上,这正是您想要的。您所要做的就是tuple再次分开。

而且我希望能够单独使用这些值。

因此,只需从中获取价值即可tuple

最简单的方法是打开包装:

a, b = select_choice()

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()

回答 2

我认为您想要的是元组。如果使用return (i, card),则可以通过以下方式获得这两个结果:

i, card = select_choice()

I think you what you want is a tuple. If you use return (i, card), you can get these two results by:

i, card = select_choice()

回答 3

def test():
    ....
    return r1, r2, r3, ....

>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)

现在,您可以使用元组完成所有您喜欢的事情。

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.


回答 4

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
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

回答 5

这是另一种选择,如果您以列表形式返回,则很容易获得值。

def select_choice():
    ...
    return [i, card]

values = select_choice()

print values[0]
print values[1]

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]

回答 6

你可以试试这个

class select_choice():
    return x, y

a, b = test()

you can try this

class select_choice():
    return x, y

a, b = test()

回答 7

您还可以使用list返回多个值。检查下面的代码

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。