没有什么能阻止您拥有多个函数,每个函数都返回您想要返回的多个结果之一。
例如,假设您在 python 中有以下函数返回一个列表。
def f(x):
L = []
for i in range(x):
L.append(x * i)
return L
它返回[0, 3, 6]
forx=3
和[0, 5, 10, 15, 20]
for x=5
。相反,你完全可以拥有
def f_nth_value(x, n):
L = []
for i in range(x):
L.append(x * i)
if n < len(L):
return L[n]
return None
然后,您可以请求给定输入的任何输出,并获取它,或者 get None
,如果没有足够的输出:
In [11]: f_nth_value(3, 0)
Out[11]: 0
In [12]: f_nth_value(3, 1)
Out[12]: 3
In [13]: f_nth_value(3, 2)
Out[13]: 6
In [14]: f_nth_value(3, 3)
In [15]: f_nth_value(5, 2)
Out[15]: 10
In [16]: f_nth_value(5, 5)
如果您必须做一些相同的工作,可能会浪费计算资源,就像在这种情况下一样。从理论上讲,可以通过返回另一个在其内部保存所有结果的函数来避免这种情况。
def f_return_function(x):
L = []
for i in range(x):
L.append(x * i)
holder = lambda n: L[n] if n < len(L) else None
return holder
所以现在我们有
In [26]: result = f_return_function(5)
In [27]: result(3)
Out[27]: 15
In [28]: result(4)
Out[28]: 20
In [29]: result(5)
传统的无类型 lambda 演算完全能够表达这个想法。(毕竟它是图灵完备的。)每当你想返回一堆值时,只需返回一个可以n-th
为 any 提供值的函数n
。
关于第二个问题,python 允许这样的语法,如果你确切地知道函数将返回多少个值。
def f(x):
L = []
for i in range(x):
L.append(x * i)
return L
In [39]: a, b, c = f(3)
In [40]: a
Out[40]: 0
In [41]: b
Out[41]: 3
In [42]: c
Out[42]: 6
In [43]: a, b, c = f(2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-43-5480fa44be36> in <module>()
----> 1 a, b, c = f(2)
ValueError: need more than 2 values to unpack
In [44]: a, b, c = f(4)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-44-d2c7a6593838> in <module>()
----> 1 a, b, c = f(4)
ValueError: too many values to unpack
最后,这是这个Lisp 教程中的一个例子:
;; in this function, the return result of (+ x x) is not assigned so it is essentially
;; lost; the function body moves on to the next form, (* x x), which is the last form
;; of this function body. So the function call only returns (* 10 10) => 100
* ((lambda (x) (+ x x) (* x x)) 10)
=> 100
;; in this function, we capture the return values of both (+ x x) and (* x x), as the
;; lexical variables SUM and PRODUCT; using VALUES, we can return multiple values from
;; a form instead of just one
* ((lambda (x) (let ((sum (+ x x)) (product (* x x))) (values sum product))) 10)
=> 20 100