1

当我们使用 def 时,我们可以使用 **kwargs 和 *args 来定义函数的动态输入

返回元组有什么类似的吗,我一直在寻找这样的东西:

def foo(data):
    return 2,1

a,b=foo(5)
a=2
b=1
a=foo(5)
a=2

但是,如果我只声明一个要解包的值,它会将整个元组发送到那里:

a=foo(5)
a=(2,1)

我可以使用“if”语句,但我想知道是否有一些不那么麻烦的东西。我也可以使用一些保持变量来存储该值,但我的返回值可能有点大,只有一些占位符。

谢谢

4

2 回答 2

2

如果您需要完全概括返回值,您可以执行以下操作:

def function_that_could_return_anything(data): 
    # do stuff
    return_args = ['list', 'of', 'return', 'values']
    return_kwargs = {'dict': 0, 'of': 1, 'return': 2, 'values': 3}
    return return_args, return_kwargs

a, b = function_that_could_return_anything(...)
for thing in  a: 
    # do stuff

for item in b.items(): 
    # do stuff

在我看来,只返回一个字典,然后使用以下方法访问参数会更简单get()

dict_return_value = foo()
a = dict_return_value.get('key containing a', None)
if a:
    # do stuff with a
于 2013-07-11T02:40:33.770 回答
0

我不太明白你在问什么,所以我会猜几个。


如果您有时想使用单个值,请考虑namedtuple

from collections import namedtuple

AAndB = namedtuple('AAndB', 'a b')

def foo(data):
    return AAndB(2,1)

# Unpacking all items.
a,b=foo(5)

# Using a single value.
foo(5).a

或者,如果您使用的是 Python 3.x,则可以使用扩展的可迭代解包来轻松解包其中的一些值:

def foo(data):
    return 3,2,1

a, *remainder = foo(5) # a==3, remainder==[2,1]
a, *remainder, c = foo(5) # a==3, remainder==[2], c==1
a, b, c, *remainder = foo(5) # a==3, b==2, c==1, remainder==[]

有时该名称_用于指示您正在丢弃该值:

a, *_ = foo(5)
于 2013-07-11T03:04:39.650 回答