我用python编写了一个函数(testFunction),其中有四个返回值:
diff1, diff2, sameCount, vennPlot
其中前3个值(在输出元组中)用于在函数内部绘制“vennPlot”。在
有人问了一个类似的问题:How can I plot output from a function which returns multiple values in Python?,但在我的例子中,我还想知道另外两件事:
稍后我可能会使用这个函数,而且似乎我需要记住返回的顺序,这样我就可以为下游工作提取正确的返回值。我说的对吗?如果是这样,有没有比output[1]或output[2]更好的引用元组返回的方法?(输出=testFunction(…))
一般来说,一个函数有多个输出是否合适?(例如,在我的例子中,我可以返回前三个值并在函数之外绘制venn图。)
非常感谢你的帮助。在
从技术上讲,每个函数只返回一个值;但是,该值可以是元组、列表或其他包含多个值的类型。在
也就是说,您可以返回一些使用值顺序以外的东西来区分它们的值。您可以返回dict:
也可以定义命名元组:
^{pr2}$似乎您是正确的(取决于您的用例)。在
您可以使用
namedtuple
:docs或者-如果顺序不重要-您可以返回一个字典,这样就可以按名称访问值。在
当然,只要有文档记录,那么它就是函数的功能,程序员就知道如何处理返回值。在
要回答第一个问题,您可以将从函数返回的元组解压为:
其次,一个函数的多个输出没有什么问题,不过为了清晰起见,通常最好避免在同一个函数中使用多个
return
语句。在相关问题 更多 >
编程相关推荐