我有以下行(注意:convert函数返回一个数组):
question, answer = convert(snippet, phrase)
这是否会将数组中的前两个值分别分配给question
和answer
变量?
答案 0 :(得分:0)
如果函数返回至少两个值的列表,则可以执行以下操作:
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)
答案 1 :(得分:0)
这在Python中被称为 unpacking 。
a, b, c = 1, 2, 3
# a -> 1
# b -> 2
# c -> 3