Python 如何从一个函数返回多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39345995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:09:49  来源:igfitidea点击:

How does Python return multiple values from a function?

pythonfunctionpython-3.xreturn

提问by User_Targaryen

I have written the following code:

我编写了以下代码:

class FigureOut:
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]

   def getName(self):
      return self.first_name, self.last_name

f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)

I get the following Output:

我得到以下输出:

('Allen', 'Solly')

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple valuesand then returns it from the function?

每当python中的函数返回多个值时,它是否总是将多个值转换为多个值的列表,然后从函数中返回它?

Is the whole process same as converting the multiple values to a listexplicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?

整个过程是否与将多个值list显式转换为 a然后返回列表相同,例如在 JAVA 中,因为在 JAVA 中只能从函数返回一个对象?

回答by Dimitris Fasarakis Hilliard

Since the return statement in getNamespecifies multiple elements:

由于中的 return 语句getName指定了多个元素

def getName(self):
   return self.first_name, self.last_name

Python will return a container object that basically contains them.

Python 将返回一个基本上包含它们的容器对象。

In this case, returning a comma separatedset of elements creates a tuple. Multiple values can only be returned inside containers.

在这种情况下,返回逗号分隔一组元素会创建一个 tuple。多个值只能在容器内返回

Let's use a simpler function that returns multiple values:

让我们使用一个更简单的函数来返回多个值:

def foo(a, b):
    return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

您可以查看使用dis.disPython 字节码的反汇编器生成的字节码。对于没有任何括号的逗号分隔值,它看起来像这样:

>>> import dis
>>> def foo(a, b):
...     return a,b        
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FASTand then a BUILD_TUPLE(grabbing the previous 2elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

如您所见,这些值首先加载到内部堆栈中LOAD_FAST,然后生成BUILD_TUPLE(抓取2放置在堆栈上的先前元素)。由于存在逗号,Python 知道要创建一个元组。

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LISTis going to be issued following the same semantics as it's tuple equivalent:

您也可以使用 指定另一种返回类型,例如列表[]。对于这种情况,BUILD_LIST将按照与元组等效的相同语义发出a :

>>> def foo_list(a, b):
...     return [a, b]
>>> dis.dis(foo_list)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples ()can be omitted if there's at least one comma). []creates lists and {}sets. Dictionaries need key:valpairs.

返回的对象类型实际上取决于括号的存在(()如果至少有一个逗号,元组可以省略)。[]创建列表和{}集合。字典需要key:val成对。

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

总而言之,返回了一个实际对象。如果该对象是容器类型,则它可以包含多个值,给人以返回多个结果的印象。通常的方法是直接解压缩它们:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)


As an aside to all this, your Java ways are leaking into Python :-)

顺便说一句,您的 Java 方式正在泄漏到 Python 中 :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

在 Python 中编写类时不要使用 getter,请使用properties. 属性是管理属性的惯用方式,有关这些的更多信息,请参阅此处的不错答案。

回答by joc

From Python Cookbook v.30

来自Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun()returns multiple values, a tupleis actually being created.It looks a bit peculiar, but it's actually the comma that forms a tuple, not the parentheses

虽然看起来myfun()返回多个值,但tuple实际上正在创建一个。看起来有点奇怪,但实际上形成元组的是逗号,而不是括号

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

所以是的,Python 中发生的是从多个逗号分隔值到元组的内部转换,反之亦然。

Though there's no equivalent in javayou can easily create this behaviour using array's or some Collections like Lists:

尽管在java 中没有等价物,但您可以使用array's 或Collection类似Lists 的一些s轻松创建此行为:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

以这种方式执行:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

结果:

sum = 15
rest = 5

回答by Kalpesh Dusane

Here It is actually returning tuple.

这里它实际上正在返回tuple

If you execute this code in Python 3:

如果您在 Python 3 中执行此代码:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

输出 :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b]instead of return a,band execute :

但是,如果您更改代码行return [a,b]而不是return a,b执行:

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

输出 :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

它只返回包含多个值的单个对象。

There is another alternative to returnstatement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

return返回多个值的语句还有另一种替代方法,请使用yield(要查看详细信息,请参阅此Python 中的“yield”关键字有何作用?

Sample Example :

示例示例:

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

输出 :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

回答by Stop harming Monica

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_nameevaluates to a tuple and that tuple is the actual value the function is returning.

Python 函数总是返回一个唯一的值。逗号运算符是元组的构造函数,因此self.first_name, self.last_name计算结果为元组,而该元组是函数返回的实际值。

回答by Junsuk Park

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a listof multiple values and then returns it from the function??

每当python中的函数返回多个值时,它是否总是将多个值转换为多个值的列表,然后从函数中返回它??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

我只是添加一个名称并打印从函数返回的结果。结果的类型是“元组”。

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)



I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

不知道大家有没有听说过“头等舱功能”。Python 是具有“一流功能”的语言

I hope my answer could help you. Happy coding.

希望我的回答能帮到你。快乐编码。

回答by Ghazal

mentioned also here, you can use this:

这里也提到,你可以使用这个:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2