如何从 Python 中的函数返回两个值? [英] How can I return two values from a function in Python?

查看:152
本文介绍了如何从 Python 中的函数返回两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

而且我希望能够单独使用这些值.当我尝试使用 return i, card 时,它返回一个 tuple 而这不是我想要的.

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.

推荐答案

你不能返回两个值,但你可以返回一个 tuple 或一个 list 并在之后解压电话:

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

在线return i,card i,card 表示创建一个元组.你也可以使用像 return (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().

如果您想返回两个以上的值,请考虑使用 命名元组.它将允许函数的调用者通过名称访问返回值的字段,这更具可读性.您仍然可以通过索引访问元组的项目.例如,在 Schema.loads 方法中,Marshmallow 框架返回一个 UnmarshalResult 这是一个 namedtuple.所以你可以这样做:

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

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

在其他情况下,您可能会从您的函数返回一个 dict:

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

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

但您可能需要考虑返回一个实用程序类(或 Pydantic/dataclass 模型实例)的实例,它包装您的数据:

But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), 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)

这篇关于如何从 Python 中的函数返回两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆