如何从函数返回多个值? [关闭] - How do I return multiple values from a function? [closed]

问题:

Closed . 已关闭 This question is opinion-based . 这个问题是基于观点的 It is not currently accepting answers. 它当前不接受答案。

Want to improve this question? 想改善这个问题吗? Update the question so it can be answered with facts and citations by editing this post . 更新问题,以便经过编辑此帖子以事实和引用的形式回答。 html

Closed last year . 去年关闭。 python

The canonical way to return multiple values in languages that support it is often tupling . 用支持它的语言返回多个值的规范方法一般是麻烦的 express

Option: Using a tuple 选项:使用元组

Consider this trivial example: 考虑下面这个简单的例子: 编程

def f(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return (y0, y1, y2)

However, this quickly gets problematic as the number of values returned increases. 可是,随着返回值的数量增长,这很快就会成为问题。 What if you want to return four or five values? 若是要返回四个或五个值怎么办? Sure, you could keep tupling them, but it gets easy to forget which value is where. 固然,您能够继续修改它们,可是很容易忘记哪一个值在哪里。 It's also rather ugly to unpack them wherever you want to receive them. 在任何要接收它们的地方打开它们的包装也是很丑陋的。 app

Option: Using a dictionary 选项:使用字典

The next logical step seems to be to introduce some sort of 'record notation'. 下一步的逻辑步骤彷佛是引入某种“记录符号”。 In Python, the obvious way to do this is by means of a dict . 在Python中,最明显的方法是经过dict 框架

Consider the following: 考虑如下: less

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0': y0, 'y1': y1 ,'y2': y2}

(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.) (请注意,y0,y1和y2只是抽象标识符。正如所指出的,实际上,您将使用有意义的标识符。) ide

Now, we have a mechanism whereby we can project out a particular member of the returned object. 如今,咱们有了一种机制,能够投影出返回对象的特定成员。 For example, 例如, 函数式编程

result['y0']

Option: Using a class 选项:使用课程

However, there is another option. 可是,还有另外一种选择。 We could instead return a specialized structure. 相反,咱们能够返回一个特殊的结构。 I've framed this in the context of Python, but I'm sure it applies to other languages as well. 我已经在Python的上下文中对此进行了框架化,可是我确信它也适用于其余语言。 Indeed, if you were working in C this might very well be your only option. 确实,若是您使用C语言工做,那么这极可能是您惟一的选择。 Here goes: 开始: 函数

class ReturnValue:
  def __init__(self, y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return ReturnValue(y0, y1, y2)

In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue . 在Python中,前两个在管道方面可能很是类似-毕竟{ y0, y1, y2 }最终只是返回ReturnValue的内部__dict__中的条目。

There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. Python为小对象提供了__slots__属性,这是另一项功能。 The class could be expressed as: 该类能够表示为:

class ReturnValue(object):
  __slots__ = ["y0", "y1", "y2"]
  def __init__(self, y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

From the Python Reference Manual : Python参考手册中

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. __slots__声明采用一系列实例变量,并在每一个实例中仅保留足够的空间来容纳每一个变量的值。 Space is saved because __dict__ is not created for each instance. 由于没有为每一个实例建立__dict__因此能够节省空间。

Option: Using a dataclass (Python 3.7+) 选项:使用数据类 (Python 3.7+)

Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools: 使用Python 3.7的新数据类,返回一个具备自动添加的特殊方法,键入和其余有用工具的类:

@dataclass
class Returnvalue:
    y0: int
    y1: float
    y3: int

def total_cost(x):
    y0 = x + 1
    y1 = x * 3
    y2 = y0 ** y3
    return ReturnValue(y0, y1, y2)

Option: Using a list 选项:使用列表

Another suggestion which I'd overlooked comes from Bill the Lizard: 我忽略的另外一个建议来自蜥蜴人比尔:

def h(x):
  result = [x + 1]
  result.append(x * 3)
  result.append(y0 ** y3)
  return result

This is my least favorite method though. 这是我最不喜欢的方法。 I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. 我想我被Haskell所污染,可是混合类型列表的想法一直让我感到不舒服。 In this particular example the list is -not- mixed type, but it conceivably could be. 在此特定示例中,列表为“非混合”类型,但能够想象是这样。

A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. 据我所知,以这种方式使用的列表实际上对元组没有任何好处。 The only real difference between lists and tuples in Python is that lists are mutable , whereas tuples are not. Python中列表和元组之间的惟一真正区别是列表是可变的 ,而元组则不是。

I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types. 我我的倾向于继承函数式编程的约定:对任何数量的相同类型的元素使用列表,对固定数量的预约类型的元素使用元组。

Question

After the lengthy preamble, comes the inevitable question. 在冗长的序言以后,出现了不可避免的问题。 Which method (do you think) is best? (您认为)哪一种方法最好?

I've typically found myself going the dictionary route because it involves less set-up work. 我一般发现本身走了字典路线,由于它涉及的设置工做较少。 From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. 可是,从类型的角度来看,您最好走类路线,由于这能够帮助您避免混淆字典所表明的含义。

On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces , at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. 另外一方面,在Python社区中,有些人认为隐式接口应该比显式接口更可取 ,此时,对象的类型其实是不相关的,由于您基本上是依赖于相同属性的约定将始终具备相同的含义。

So, how do -you- return multiple values in Python? 那么,如何在Python中返回多个值?


解决方案:

参考一: https://stackoom.com/question/1UJv/如何从函数返回多个值-关闭
参考二: https://oldbug.net/q/1UJv/How-do-I-return-multiple-values-from-a-function-closed
相关文章
相关标签/搜索