假设我有一个Python函数,在一个元组中返回多个值:
def func():
return 1, 2
有没有一种很好的方法来忽略一个结果,而不是仅仅分配给一个临时变量?如果我只对第一个值感兴趣,有没有比这更好的方法:
x, temp = func()
假设我有一个Python函数,在一个元组中返回多个值:
def func():
return 1, 2
有没有一种很好的方法来忽略一个结果,而不是仅仅分配给一个临时变量?如果我只对第一个值感兴趣,有没有比这更好的方法:
x, temp = func()
当前回答
最好的解决方案可能是为事物命名,而不是返回毫无意义的元组(除非在返回项的顺序后面有一些逻辑)。例如,你可以使用字典:
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
如果你的字典/元组中的对象是强绑定在一起的,那么为它定义一个类可能是一个好主意。这样,您还可以定义更复杂的操作。随之而来的一个自然问题是:什么时候应该在Python中使用类?
python的最新版本(≥3.7)都有数据类,你可以用很少的代码行来定义类:
from dataclasses import dataclass
@dataclass
class Coordinates:
lat: float = 0
lng: float = 0
def func():
return Coordinates(lat=1, lng=2)
latitude = func().lat
数据类相对于namedtuple的主要优势是更容易扩展,但还有其他不同之处。注意,默认情况下,数据类是可变的,但您可以使用@dataclass(frozen=True)而不是@dataclass来强制它们是不可变的。
这里有一个视频,可以帮助您为您的用例选择正确的数据类。
其他回答
如果您愿意,可以用更少的语法忽略除第一个变量以外的所有变量。如果我们以你为例
# 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]
当你从一个函数中有很多输出,而你不想多次调用它时,我认为选择结果的最清晰的方法是:
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
一种常见的约定是使用“_”作为您希望忽略的元组元素的变量名。例如:
def f():
return 1, 2, 3
_, _, x = f()
三个简单的选择。
明显的
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)