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

def func():
    return 1, 2

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

x, temp = func()

当前回答

三个简单的选择。

明显的

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)

其他回答

这不是对这个问题的直接回答。相反,它回答了这个问题:“我如何从许多可能的选项中选择一个特定的函数输出?”

如果您能够编写函数(即,它不在您不能修改的库中),那么添加一个输入参数,指示您想从函数中得到什么。让它成为一个带有默认值的命名参数,这样在“常见情况”下你甚至不需要指定它。

    def fancy_function( arg1, arg2, return_type=1 ):
        ret_val = None
        if( 1 == return_type ):
            ret_val = arg1 + arg2
        elif( 2 == return_type ):
            ret_val = [ arg1, arg2, arg1 * arg2 ]
        else:
            ret_val = ( arg1, arg2, arg1 + arg2, arg1 * arg2 ) 
        return( ret_val )

该方法给出了关于所需输出的“高级警告”函数。因此,它可以跳过不需要的处理,只做获得所需输出所需的工作。另外,因为Python是动态类型,所以返回类型可以改变。注意这个例子是如何返回标量、列表或元组的…你喜欢什么都行!

这似乎是我最好的选择:

val1, val2, ignored1, ignored2 = some_function()

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

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

def func():
    return 1, 2

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

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


# 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]