我想知道是否有一種方法可以將函式的多個輸出放入串列中。我對在函式內部創建串列不感興趣,因為我不會浪費您的時間。
我知道我期望有多少個輸出變數,但只能通過使用注釋[“return”] 運算式(或任何你稱之為的,對不起,對于 noobish 術語),這會因情況而異,這就是為什么我需要這個是動態的。
我知道我可以使用函式(* myList)將串列用作多個變數,但我感興趣的是在從函式接收回傳值時是否有一種等效的方法。
干杯!
偽代碼:
function():
x = 1
y = 2
return x, y
variables = function()
print(variables[0], " and ", variables[1]
result should be = "1 and 2"
uj5u.com熱心網友回復:
是的,使用解包賦值運算式 ex a,b,c= myfunction(...),您可以將 * 放在其中一個中,以使其采用可變數量的引數
>>> a,b,c=range(3) #if you know that the thing contains exactly 3 elements you can do this
>>> a,b,c
(0, 1, 2)
>>> a,b,*c=range(10) #for when you know that there at least 2 or more the first 2 will be in a and b, and whatever else in c which will be a list
>>> a,b,c
(0, 1, [2, 3, 4, 5, 6, 7, 8, 9])
>>> a,*b,c=range(10)
>>> a,b,c
(0, [1, 2, 3, 4, 5, 6, 7, 8], 9)
>>> *a,b,c=range(10)
>>> a,b,c
([0, 1, 2, 3, 4, 5, 6, 7], 8, 9)
>>>
另外你可以從一個函式回傳任何你想要的,一個串列、一個元組、一個字典等,但只有一件事
>>> def fun():
return 1,"boo",[1,2,3],{1:10,3:23}
>>> fun()
(1, 'boo', [1, 2, 3], {1: 10, 3: 23})
>>>
在這個例子中,它回傳一個包含所有這些東西的元組,因為,它是元組建構式,所以它首先創建一個元組(你的一件事)并回傳它
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474883.html
標籤:python-3.x 列表 功能 返回
