问题:忽略python多个返回值

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

def func():
    return 1, 2

有没有一种好的方法可以忽略其中一个结果,而不仅仅是分配给一个临时变量?假设我只对第一个值感兴趣,是否有比这更好的方法:

x, temp = func()

Say I have a Python function that returns multiple values in a tuple:

def func():
    return 1, 2

Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:

x, temp = func()

回答 0

一种常见的约定是对您要忽略的元组的元素使用“ _”作为变量名。例如:

def f():
    return 1, 2, 3

_, _, x = f()

One common convention is to use a “_” as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()

回答 1

您可以使用x = func()[0]返回第一个值,x = func()[1]返回第二个值,依此类推。

如果您想一次获取多个值,请使用x, y = func()[2:4]

You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.

If you want to get multiple values at a time, use something like x, y = func()[2:4].


回答 2

如果您使用的是Python 3,则可以在变量(在作业的左侧)之前使用星号,以使其成为解压缩列表。

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

If you’re using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.

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

回答 3

请记住,当您返回多个项目时,您实际上是在返回一个元组。因此,您可以执行以下操作:

def func():
    return 1, 2

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

Remember, when you return more than one item, you’re really returning a tuple. So you can do things like this:

def func():
    return 1, 2

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

回答 4

通常的做法是使用哑变量_(单个下划线),正如前面在此处指出的那样。

但是,为了避免与该变量名的其他用法冲突(请参阅响应)__,如ncoghlan所指出的那样,最好使用(双下划线)代替一次性变量。例如:

x, __ = func()

The common practice is to use the dummy variable _ (single underscore), as many have indicated here before.

However, to avoid collisions with other uses of that variable name (see this response) it might be a better practice to use __ (double underscore) instead as a throwaway variable, as pointed by ncoghlan. E.g.:

x, __ = func()

回答 5

三个简单的选择。

明显

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)

Three simple choices.

Obvious

x, _ = func()

x, junk = func()

Hideous

x = func()[0]

And there are ways to do this with a decorator.

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

func0= val0(func)

回答 6

最好的解决方案可能是命名事物,而不是返回无意义的元组。除非返回的项目的顺序背后有逻辑。

def func():
    return {'lat': 1, 'lng': 2}

latitude = func()['lat']

如果您想添加有关返回内容的更多信息,甚至可以使用namedtuple(不仅仅是字典,这些是坐标):

from collections import namedtuple 

Coordinates = namedtuple('Coordinates', ['lat', 'lng'])

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat

如果字典/元组中的对象紧密地绑在一起,那么甚至最好为其定义一个类。这样,您还可以定义此类型对象之间的交互,并提供有关如何使用它们的API。接下来的自然问题是:什么时候应该在Python中使用类?

The best solution probably is to name things instead of returning meaningless tuples (unless there is some logic behind the order of the returned items). You can for example use a dictionary:

def func():
    return {'lat': 1, 'lng': 2}
    
latitude = func()['lat']

You could even use namedtuple if you want to add extra information about what you are returning (it’s not just a dictionary, it’s a pair of coordinates):

from collections import namedtuple 

Coordinates = namedtuple('Coordinates', ['lat', 'lng'])

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat

If the objects within your dictionary/tuple are strongly tied together then it may be a good idea to even define a class for it. That way you’ll also be able to define more complex operations. A natural question that follows is: When should I be using classes in Python?

Most recent versions of python (≥ 3.7) have dataclasses which you can use to define classes with very few lines of code:

from dataclasses import dataclass

@dataclass
class Coordinates:
    lat: float = 0
    lng: float = 0

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat

The primary advantage of dataclasses over namedtuple is that its easier to extend, but there are other differences. Note that by default, dataclasses are mutable, but you can use @dataclass(frozen=True) instead of @dataclass to force them being immutable.


回答 7

在我看来,这似乎是最佳选择:

val1, val2, ignored1, ignored2 = some_function()

它不是神秘的或丑陋的(就像func()[index]方法一样),并且清楚地说明了您的目的。

This seems like the best choice to me:

val1, val2, ignored1, ignored2 = some_function()

It’s not cryptic or ugly (like the func()[index] method), and clearly states your purpose.


回答 8

这不是问题的直接答案。而是回答了这个问题:“如何从许多可能的选项中选择特定的函数输出?”。

如果您能够编写该函数(即它不在库中,则无法修改),则添加一个输入自变量,以指示您要从该函数中获取的内容。将其设为具有默认值的命名参数,这样,在“普通情况”下,您甚至不必指定它。

    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进行动态类型化,所以返回类型可以更改。请注意,示例如何返回标量,列表或元组……随您便!

This is not a direct answer to the question. Rather it answers this question: “How do I choose a specific function output from many possible options?”.

If you are able to write the function (ie, it is not in a library you cannot modify), then add an input argument that indicates what you want out of the function. Make it a named argument with a default value so in the “common case” you don’t even have to specify it.

    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 )

This method gives the function “advanced warning” regarding the desired output. Consequently it can skip unneeded processing and only do the work necessary to get your desired output. Also because Python does dynamic typing, the return type can change. Notice how the example returns a scalar, a list or a tuple… whatever you like!


回答 9

如果这是您一直使用的函数,但始终舍弃第二个参数,那么我认为无需使用第二个返回值就可以为该函数创建别名不会太麻烦lambda

def func():
    return 1, 2

func_ = lambda: func()[0] 

func_()  # Prints 1 

If this is a function that you use all the time but always discard the second argument, I would argue that it is less messy to create an alias for the function without the second return value using lambda.

def func():
    return 1, 2

func_ = lambda: func()[0] 

func_()  # Prints 1 

回答 10

当您从一个函数获得许多输出并且不想多次调用它时,我认为选择结果的最简单方法是:

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

When you have many output from a function and you don’t want to call it multiple times, I think the clearest way for selecting the results would be :

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

As a minimum working example, also demonstrating that the function is called only once :

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

And the values are as expected :

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

For convenience, Python list indexes can also be used :

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

Returns : a = 3 and b = 12


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。