简体   繁体   English

python函数是否可以返回多于1的值?

[英]Is it possible for a python function to return more than 1 value?

我正在学习python中函数的使用,并想知道是否可以返回超过1的值。

You can return the values you want to return as a tuple. 您可以返回要作为元组返回的值。

Example: 例:

>>> def f():
...     return 1, 2, 3
... 
>>> a, b, c = f()
>>> a
1
>>> b
2
>>> c
3
>>>

Python has some parameter unpacking which is cool. Python有一些参数解包很酷。 So although you can only return one value, if it is a tuple, you can unpack it automatically: 因此,虽然您只能返回一个值,但如果它是一个元组,您可以自动解压缩它:

>>> def foo():
...     return 1, 2, 3, 4 # Returns a tuple
>>> foo()
(1, 2, 3, 4)

>>> a, b, c, d = foo()
>>> a
1
>>> b
2
>>> c
3
>>> d
4

In Python 3 you have more advanced features: 在Python 3中,您有更多高级功能:

>>> a, *b = foo()
>>> a
1
>>> b
[2, 3, 4]
>>> *a, b = foo()
>>> a
[1, 2, 3]
>>> b
4
>>> a, *b, c = foo()
>>> a
1
>>> b
[2, 3]
>>> c
4

But that doesn't work in Python 2. 但这在Python 2中不起作用。

def two_values():
    return (1, 2)

(a, b) = two_values()

Yes. 是。

def f():
   return 1, 2


x, y = f()
# 1, 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM