在 Python 中处理函数的多个返回

Hel*_*ene 1 python

我在 Python 中编写了一个具有四个返回值的函数 (testFunction):

diff1, diff2, sameCount, vennPlot
Run Code Online (Sandbox Code Playgroud)

其中前 3 个值(在输出元组中)用于在函数内部绘制“vennPlot”。

有人问了一个类似的问题:如何绘制在 Python 中返回多个值的函数的输出?,但就我而言,我还想知道另外两件事:

  1. 我以后可能会使用这个函数,似乎我需要记住返回的顺序,以便我可以为下游工作提取正确的返回。我在这里正确吗?如果是这样,是否有比 output[1] 或 output[2] 更好的方法来引用元组返回?(输出=testFunction(...))

  2. 一般来说,一个函数有多个输出是否合适?(例如,在我的情况下,我可以只返回前三个值并在函数之外绘制维恩图。)

che*_*ner 5

从技术上讲,每个函数都只返回一个值;但是,该值可以是元组、列表或其他包含多个值的类型。

也就是说,您可以返回一些使用值的顺序以外的东西来区分它们的东西。你可以返回一个字典:

def testFunction(...):
    ...
    return dict(diff1=..., diff2=..., sameCount=..., venn=...)

x = testFunction(...)
print(x['diff1'])
Run Code Online (Sandbox Code Playgroud)

或者你可以定义一个命名元组:

ReturnType = collections.namedtuple('ReturnType', 'diff1 diff2 sameCount venn')


def testFunction(...):
    ...
    return ReturnType(diff1=..., diff2=..., sameCount=..., venn=...)

x = testFunction(...)
print(x.diff1)  # or x[0], if you still want to use the index
Run Code Online (Sandbox Code Playgroud)