如何在Python中返回多个值? [英] How do you return multiple values in Python?

查看:177
本文介绍了如何在Python中返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以支持它的语言返回多个值的规范方式通常是 tupling

The canonical way to return multiple values in languages that support it is often tupling.

考虑这个简单的例子:

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

但是,这很快就会出现问题,因为值的数量返回增加。如果你想返回四个或五个值怎么办?当然,你可以保持tupling他们,但它很容易忘记哪个值是哪里。

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.

下一个逻辑步骤似乎是引入某种记录符号。在python中,显而易见的方法是通过 dict

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.

请考虑以下事项:

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

(edit-只是为了清楚起见,y0,y1和y2只是作为抽象标识符。正如所指出的,实际上你会使用有意义的标识符)

(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)

现在,我们有一个机制,我们可以计算出一个特定的成员返回的对象。例如,

Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,

result['y0']



选项:使用类



但是,还有另一个选项。我们可以返回一个专门的结构。我已经在Python的上下文框架,但我确信它也适用于其他语言。事实上,如果你在C工作,这可能是你唯一的选择。这里:

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. Indeed, if you were working in C this might very well be your only option. Here goes:

class ReturnValue(object):
  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)

在python中,前两个可能在plumbing方面非常相似 - 在所有 {y0,y1,y2} ReturnValue 的内部 __ dict __ 中的条目。

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还提供了一个额外的功能,对于微小的对象, __ slots __ 属性。类可以表示为:

There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. 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

Python参考手册


__ slots __ 声明采用一系列实例变量,并在每个实例中保留足够的空间以容纳每个变量的值。因为 __ dict __ 没有为每个实例创建,所以节省了空间。

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.



使用列表



我忽略的另一个建议来自比尔蜥蜴:

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

这是我最不喜欢的方法。我想我受到暴露在Haskell的污染,但混合类型列表的想法一直对我感到不舒服。在该特定示例中,列表是非混合类型,但可以想象到的是。用这种方式列出的列表根据我可以告诉的元组实际上没有获得任何东西。 Python中的列表和元组之间唯一的区别是列表是 mutable ,wheras tuples不是。我个人倾向于从函数式编程中继承约定:使用相同类型的任何数量的元素的列表,以及固定数量的预定类型的元素的元组。

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. 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, wheras tuples are not. 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.

在冗长的序言之后,出现了不可避免的问题。

After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?

我通常发现自己在字典路由,因为它涉及更少的设置工作。然而,从类型的角度来看,你可能最好去类路由,因为这可能有助于避免混淆字典表示什么。另一方面,Python社区中有一些人感觉到隐含接口应该优先于显式接口,在这一点上,对象的类型真的是不相关的,因为你基本上依赖于相同的属性总是具有相同的意义的约定。

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?

推荐答案

命名元组。另请参阅类似内置示例的 os.stat

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

>>> 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

这篇关于如何在Python中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆