引用python中函数的第一个返回值



我想引用函数的第一个返回元素。

我有一个函数返回两个值:x2和y2。

在下一个函数中,我想引用第一个值。怎么做呢?这里有一个我尝试的例子:
def helper1(x,y):
return x*2,y*2
def helper2(x,y):
helper1(x,y)
a = 2/helper1[0] #here I try to refer to the first element returned of helper1, but doesn't work :( 
return a

任何想法?

def helper1(x,y):
return x*2, y*2
def helper2(x,y):
a = 2/helper1(x, y)[0]   # how to access to the 1st value of helper1
return a  # no idea of what is a
print(helper2(3, 4))
#0.3333333333333333

你只是把函数放在那里,而不是函数的结果。

在这里我调用函数并在除法之前得到[0]。顺便说一下,你是想在引用传递中给输入赋值吗?风格吗?因为我觉得这行不通。

def helper1(x,y):
return x*2,y*2
def helper2(a,x,y):
a = 2/(helper1(x,y)[0]) #helper1(x,y)[0], not helper1[0]

试试这样写:

>>> def helper2(x, y):
...     tmp = helper1(x,y)    
...     a = 2/tmp[0]

注意,您需要存储调用helper1(x,y)的结果。然后可以通过索引访问结果的第一个元素,例如tmp[0]

或者你可以写

...     a = 2/helper1(x,y)[0]

避免使用临时变量

alpha, beta = helper1(x, y)
a = 2 / alpha

最新更新