如何從函數返回多個值? [關閉] - 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
相關文章
相關標籤/搜索