【问题标题】:Dynamical output in Python FunctionsPython 函数中的动态输出
【发布时间】:2013-07-11 02:31:23
【问题描述】:

当我们使用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”语句,但我想知道是否有一些不那么麻烦的东西。我也可以使用一些保持变量来存储该值,但我的返回值可能有点大,只有一些占位符。

谢谢

【问题讨论】:

  • 如果您希望a 始终包含第一个值,那么您可以使用a = foo(5)[0]。这是您所要求的,还是您需要更通用的解决方案?
  • 您希望对您的多个结果值产生什么影响?
  • Marius,我想这就是我要找的东西,只是觉得有点 hacky,想知道是否有更复杂的方法

标签: python function output


【解决方案1】:

如果你需要完全概括返回值,你可以这样做:

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

【讨论】:

    【解决方案2】:

    我不太明白你在问什么,所以我会猜测一下。


    如果您有时想使用单个值,请考虑使用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,则可以使用 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)
    

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2021-07-31
      • 1970-01-01
      • 2012-11-05
      • 2018-07-12
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多