Python函数返回多个值的方法
通常情况下,一个函数只有一个返回值,实际上 Python 也是如此,只不过 Python 函数能以返回列表或者元组的方式,将要返回的多个值保存到序列中,从而间接实现返回多个值的目的。
因此,实现 Python 函数返回多个值,有以下 2 种方式:
因此,实现 Python 函数返回多个值,有以下 2 种方式:
- 在函数中,提前将要返回的多个值存储到一个列表或元组中,然后函数返回该列表或元组;
- 函数直接返回多个值,之间用逗号( , )分隔,Python 会自动将多个值封装到一个元组中,其返回值仍是一个元组;
def return_list():
add = [
"https://www.python.org/",
"https://docs.djangoproject.com/en/dev/",
"https://www.cnblogs.com/qingchengzi"
]
return add
def return_tuple():
return "https://www.python.org/", "https://docs.djangoproject.com/en/dev/", "https://www.cnblogs.com/qingchengzi"
print("return_list={0}".format(return_list()))
print("return_tuple={0}".format(return_tuple()))
程序执行结果为:
return_list=['https://www.python.org/', 'https://docs.djangoproject.com/en/dev/', 'https://www.cnblogs.com/qingchengzi']
return_tuple=('https://www.python.org/', 'https://docs.djangoproject.com/en/dev/', 'https://www.cnblogs.com/qingchengzi')
在此基础上,我们可以利用 Python 提供的序列解包功能,之间使用对应数量的变量,直接接收函数返回列表或元组中的多个值。这里以 retu_list() 为例:
def return_list():
add = [
"https://www.python.org/",
"https://docs.djangoproject.com/en/dev/",
"https://www.cnblogs.com/qingchengzi"
]
return add
pythonadd,shelladd,golangadd = return_list()
print("pythonadd={0}".format(pythonadd))
print("shelladd={0}".format(shelladd))
print("golanagadd={0}".format(golangadd))
程序执行结果:
pythonadd=https://www.python.org/
shelladd=https://docs.djangoproject.com/en/dev/
golanagadd=https://www.cnblogs.com/qingchengzi