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

2024-09-29 20:30:49 发布

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

我用python编写了一个函数(testFunction),其中有四个返回值:

diff1, diff2, sameCount, vennPlot

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

有人问了一个类似的问题:How can I plot output from a function which returns multiple values in Python?,但在我的例子中,我还想知道另外两件事:

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

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

非常感谢你的帮助。在


Tags: 函数outputplot绘制can例子how元组
3条回答

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

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

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

x = testFunction(...)
print(x['diff1'])

也可以定义命名元组:

^{pr2}$

I will likely to use this function later, and seems like I need to memorize the order of the returns so that I can extract the correct return for downstream work. Am I correct here?

似乎您是正确的(取决于您的用例)。在

If so, is there better ways to refer to the tuple return than do output[1], or output[2]? (output=testFunction(...))

您可以使用namedtuple:docs

或者-如果顺序不重要-您可以返回一个字典,这样就可以按名称访问值。在

Generally speaking, is it appropriate to have multiple outputs from a function? (E.g. in my case, I could just return the first three values and draw the venn diagram outside of the function.)

当然,只要有文档记录,那么它就是函数的功能,程序员就知道如何处理返回值。在

要回答第一个问题,您可以将从函数返回的元组解压为:

diff1, diff2, samecount, vennplot = testFunction(...)

其次,一个函数的多个输出没有什么问题,不过为了清晰起见,通常最好避免在同一个函数中使用多个return语句。在

相关问题 更多 >

    热门问题