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

查看:353
本文介绍了我如何从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 时,它返回一个元组,这不是我想要的。

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.

推荐答案

您不能返回两个值,但您可以返回元组 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()

在线返回我,卡 i,卡表示创建一个元组。你也可以使用括号,如 return(i,card),但元组由逗号创建,所以parens不是强制性的。但是你可以使用parens来使你的代码更具可读性,或者将元组分成多行。同样适用于 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:
    ...



or

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, ...}



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)

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

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