ChatGPT解决这个技术问题 Extra ChatGPT

如何从 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 时,它返回一个 tuple,这不是我想要的。

请提供调用此预期函数并使用其返回值的示例,以便清楚说明您不想要元组的原因。
while 循环的意义何在?
在 return 语句之前应该有一个 else: continue
是的,我也刚刚注意到这是 stackoverflow.com/questions/38508/… 的副本

w
warvariuc

您不能返回两个值,但您可以返回 tuplelist 并在调用后将其解包:

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

my_i, my_card = select_choice()

return i, cardi, card 表示创建一个元组。您也可以使用 return (i, card) 之类的括号,但元组是由逗号创建的,因此括号不是强制性的。但是您可以使用括号使您的代码更具可读性或将元组拆分为多行。这同样适用于第 my_i, my_card = select_choice() 行。

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

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

或者

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

在其他情况下,您可能会从函数中返回 dict

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

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

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)

K
Karl Knechtel

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

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

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

当我尝试使用 return i, card 时,它返回一个元组,这不是我想要的。

其实,这正是你想要的。您所要做的就是再次拆开 tuple

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

因此,只需从 tuple 中获取值。

最简单的方法是解包:

a, b = select_choice()

感谢您解释“为什么会这样”。最佳答案 imo。
h
heinrich5991

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

i, card = select_choice()

A
Amin Jalali
def test():
    ....
    return r1, r2, r3, ....

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

现在你可以用你的元组做任何你喜欢的事情了。


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

p
praveen

这是另一种选择。如果您以列表形式返回,那么获取值很简单。

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

values = select_choice()

print values[0]
print values[1]

s
samuel161

你可以试试这个

class select_choice():
    return x, y

a, b = test()

k
kaushik karan

您也可以使用 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