假设我有一个Python函数,在一个元组中返回多个值:

def func():
    return 1, 2

有没有一种很好的方法来忽略一个结果,而不是仅仅分配给一个临时变量?如果我只对第一个值感兴趣,有没有比这更好的方法:

x, temp = func()

当前回答

如果您愿意,可以用更少的语法忽略除第一个变量以外的所有变量。如果我们以你为例


# The function you are calling.
def func():
    return 1, 2

# You seem to only be interested in the first output.
x, temp = func()

我发现以下工作,

x, *_ = func()

这种方法将所有其他变量“解包”为“一次性”变量_。这样做的好处是只指定一个你想要的变量,而忽略它后面的所有变量。

然而,在许多情况下,您可能希望输出不是函数的第一个输出。在这些情况下,最好使用func()[i]来表示,其中i是您想要的输出的索引位置。在你的情况下,

# i == 0 because of zero-index.
x = func()[0]

顺便说一句,如果你想在Python 3中变得更漂亮,你可以这样做,

# This works the other way around.
*_, y = func()

你的函数只输出两个潜在变量,所以这看起来不是很强大,直到你遇到这样的情况,

def func():
    return 1, 2, 3, 4

# I only want the first and last.
x, *_, d = func()

其他回答

记住,当返回多个元素时,实际上返回的是一个元组。所以你可以这样做:

def func():
    return 1, 2

print func()[0] # prints 1
print func()[1] # prints 2

三个简单的选择。

明显的

x, _ = func()

x, junk = func()

可怕的

x = func()[0]

有很多方法可以用装饰器来做到这一点。

def val0( aFunc ):
    def pick0( *args, **kw ):
        return aFunc(*args,**kw)[0]
    return pick0

func0= val0(func)

常见的做法是使用虚拟变量_(单个下划线),正如前面许多人指出的那样。

然而,为了避免与该变量名的其他用法发生冲突(参见此响应),可能更好的做法是使用__(双下划线)作为丢弃变量,正如ncoghlan所指出的那样。例如:

x, __ = func()

如果你在使用python3,你可以在变量前使用星号(在赋值的左边),让它在解包时成为一个列表。

# Example 1: a is 1 and b is [2, 3]

a, *b = [1, 2, 3]

# Example 2: a is 1, b is [2, 3], and c is 4

a, *b, c = [1, 2, 3, 4]

# Example 3: b is [1, 2] and c is 3

*b, c = [1, 2, 3]       

# Example 4: a is 1 and b is []

a, *b = [1]

当你从一个函数中有很多输出,而你不想多次调用它时,我认为选择结果的最清晰的方法是:

results = fct()
a,b = [results[i] for i in list_of_index]

作为一个最小的工作示例,也演示了函数只被调用一次:

def fct(a):
    b=a*2
    c=a+2
    d=a+b
    e=b*2
    f=a*a
    print("fct called")
    return[a,b,c,d,e,f]

results=fct(3)
> fct called

x,y = [results[i] for i in [1,4]]

和预期的值一样:

results
> [3,6,5,9,12,9]
x
> 6
y
> 12

为了方便起见,还可以使用Python列表索引:

x,y = [results[i] for i in [0,-2]]

返回:a = 3和b = 12