How can I return two values from a function in Python?
我想从一个函数返回两个独立变量的值。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
我希望能够单独使用这些值。当我尝试使用
不能返回两个值,但可以返回
1 2 3 4 5 | def select_choice(): ... return i, card # or [i, card] my_i, my_card = select_choice() |
在线
如果要返回两个以上的值,请考虑使用命名的元组。它将允许函数的调用者按名称访问返回值的字段,这样更易于阅读。您仍然可以通过索引访问元组的项。例如,在
1 2 3 | data, errors = MySchema.loads(request.json()) if errors: ... |
或
1 2 3 4 5 | result = MySchema.loads(request.json()) if result.errors: ... else: # use `result.data` |
在其他情况下,您可以从您的函数返回一个
1 2 3 | def select_choice(): ... return {'i': i, 'card': card, 'other_field': other_field, ...} |
但您可能需要考虑返回实用程序类的实例,该实例包装了您的数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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) |
I would like to return two values from a function in two separate variables.
您希望它在呼叫端看起来是什么样的?您不能编写
值不会"在变量中"返回;这不是Python的工作方式。函数返回值(对象)。变量只是给定上下文中某个值的名称。当您调用一个函数并在某个地方分配返回值时,您所做的就是在调用上下文中为接收到的值命名。函数不会将值"放入变量"中,赋值会这样做(不要介意变量不是值的"存储",但同样,它只是一个名称)。
When i tried to to use
return i, card , it returns atuple and this is not what i want.
实际上,这正是你想要的。你所要做的就是再把埃多克斯1号[1号]拆开。
And i want to be able to use these values separately.
所以只需从
最简单的方法是解包:
1 | a, b = select_choice() |
我想你想要的是一个元组。如果您使用
1 | i, card = select_choice() |
1 2 3 4 5 6 7 | def test(): .... return r1, r2, r3, .... >> ret_val = test() >> print ret_val (r1, r2, r3, ....) |
现在你可以用你的元组做任何你喜欢的事情。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
这是另一种选择,如果您以列表的形式返回,那么很容易获得值。
1 2 3 4 5 6 7 8 | def select_choice(): ... return [i, card] values = select_choice() print values[0] print values[1] |
也可以使用list返回多个值。检查下面的代码
1 2 3 4 5 6 7 8 9 10 | 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 |