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

def func():
    return 1, 2

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

x, temp = func()

当前回答

这似乎是我最好的选择:

val1, val2, ignored1, ignored2 = some_function()

它并不晦涩或丑陋(像func()[index]方法那样),并且清楚地阐明了您的目的。

其他回答

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


# 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()

如果你在使用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]

三个简单的选择。

明显的

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()

如果这是一个一直使用但总是丢弃第二个参数的函数,我认为为没有使用lambda的第二个返回值的函数创建别名不那么混乱。

def func():
    return 1, 2

func_ = lambda: func()[0] 

func_()  # Prints 1