構造一個可以返回多個值的函數
能返回多個值,函數直接return一個元組就行了。例如:
>>> def myfun():
... return 1, 2, 3
...
>>> a, b, c = myfun()
>>> a
1
>>> b
2
>>> c
3
儘管myfun()看上去返回了多個值,實際上是先創建了一個元組然後返回的。 這個語法看上去比較奇怪,實際上我們使用的是逗號來生成一個元組,而不是用括號。比如下面的:
>>> a = (1, 2) # With parentheses
>>> a
(1, 2)
>>> b = 1, 2 # Without parentheses
>>> b
(1, 2)
當我們調用返回一個元組的函數的時候 ,通常我們會將結果賦值給多個變量,就像上面的那樣
>>> x = myfun()
>>> x
(1, 2, 3)