2016-08-06 4 views
2

に変数を割り当てるは、私は、次の行(:変換関数は、配列を返す注):有しアレイ

question, answer = convert(snippet, phrase) 

このそれぞれquestionanswer変数に配列の最初の2つの値を割り当てていますか?

question, answer = convert(snippet, phrase)[:2] 
#or 
question, answer, *_ = convert(snippet, phrase) 

をたとえば:関数は、少なくとも2つの値のリストを返した場合、あなたが行うことができます

+2

あなたは自分で解決策を見つけようとしましたか? – technico

答えて

0

# 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) 
0

これはPythonでunpackingと呼ばれています。

a, b, c = 1, 2, 3 
# a -> 1 
# b -> 2 
# c -> 3 
関連する問題