2
我有下面這行(注:轉換函數返回一個數組):變量賦值給一個數組
question, answer = convert(snippet, phrase)
這是否指定數組中的前兩個值分別question
和answer
變量?
我有下面這行(注:轉換函數返回一個數組):變量賦值給一個數組
question, answer = convert(snippet, phrase)
這是否指定數組中的前兩個值分別question
和answer
變量?
如果函數返回至少兩個值的列表,你可以這樣做:
question, answer = convert(snippet, phrase)[:2]
#or
question, answer, *_ = convert(snippet, phrase)
例如:
# valid multiple assignment/unpacking
x,y = 1, 2
x,y = [1,2,3][:2]
x,y, *z = [1, 2, 3, 4] # * -> put the rest as the list to z
x, y, *_z = [1, 2, 3, 4] # similar as above but, uses a 'throwaway' variable _
#invalid
x, y = 1, 2, 3 #ValueError: too many values to unpack (expected 2)
這在Python被稱爲unpacking。
a, b, c = 1, 2, 3
# a -> 1
# b -> 2
# c -> 3
你試圖自己找到解決方案的是什麼? – technico