7. 函数和 lambda 表达式 7.11. Python 函数怎样返回多个值?

通常情况下,一个函数只有一个返回值,实际上 Python 也是如此,只不过 Python 函数能以返回列表或者元组的方式,将要返回的多个值保存到序列中,从而间接实现返回多个值的目的。

因此,实现 Python 函数返回多个值,有以下 2 种方式:

  1. 在函数中,提前将要返回的多个值存储到一个列表或元组中,然后函数返回该列表或元组;
  2. 函数直接返回多个值,之间用逗号( , )分隔,Python 会自动将多个值封装到一个元组中,其返回值仍是一个元组。

下面程序演示了以上 2 种实现方法:

def retu_list() :
    add = ["http://c.biancheng.net/python/",\
            "http://c.biancheng.net/shell/",\
            "http://c.biancheng.net/golang/"]
    return add
def retu_tuple() :
    return "http://c.biancheng.net/python/",\
           "http://c.biancheng.net/golang/",\
           "http://c.biancheng.net/golang/"
print("retu_list = ",retu_list())
print("retu_tuple = ",retu_tuple())

程序执行结果为:

retu_list =  ['http://c.biancheng.net/python/', 'http://c.biancheng.net/shell/', 'http://c.biancheng.net/golang/']
retu_tuple =  ('http://c.biancheng.net/python/', 'http://c.biancheng.net/golang/', 'http://c.biancheng.net/golang/')

在此基础上,我们可以利用 Python 提供的序列解包功能,之间使用对应数量的变量,直接接收函数返回列表或元组中的多个值。这里以 retu_list() 为例:

def retu_list() :
    add = ["http://c.biancheng.net/python/",\
            "http://c.biancheng.net/shell/",\
            "http://c.biancheng.net/golang/"]
    return add
pythonadd,shelladd,golangadd = retu_list()
print("pythonadd=",pythonadd)
print("shelladd=",shelladd)
print("golangadd=",golangadd)

程序执行结果为:

pythonadd= http://c.biancheng.net/python/
shelladd= http://c.biancheng.net/shell/
golangadd= http://c.biancheng.net/golang/
posted @ 2023-03-21 11:12  HopeLive  阅读(108)  评论(0)    收藏  举报