Python函数中的动态输出

2024-04-26 23:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们使用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)

我可以使用“如果”语句,但我想知道是否有不那么麻烦的语句。我也可以使用一些hold变量来存储这个值,但是我的返回值可能有点大,因为只有一些占位符。你知道吗

谢谢


Tags: 函数声明datareturn定义foodefargs
2条回答

我不太明白你到底在问什么,所以我来猜猜看。你知道吗


如果有时要使用单个值,请考虑^{}

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

或者,如果您使用的是python3.x,那么extended iterable unpacking可以轻松地解压一些值:

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)

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

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

相关问题 更多 >