函数common()
返回两个列表。我想将两个列表存储在两个不同的变量中(例如result1
和result2
)。我该怎么办?
我尝试过,result1, result2 = common(a,b)
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #1st input
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #2nd input
a_dup = []
b_dup = []
def common(list1,list2) :
for x in list1 :
if list1.count(x) == 1 :
a_dup.append(x)
return a_dup
for x in list2 :
if list2.count(x) == 1 :
b_dup.append(x)
return b_dup
result1, result2 = common(a,b)
出现以下错误:
ValueError: too many values to unpack (expected 2)
答案 0 :(得分:2)
当函数返回值时,此后它将停止任何操作。因此,return a_dup
之后的所有代码都将被放弃。如果您想一次返回两个值,请执行以下操作:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #1st input
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #2nd input
a_dup = []
b_dup = []
def common(list1,list2) :
for x in list1 :
if list1.count(x) == 1 :
a_dup.append(x)
for x in list2 :
if list2.count(x) == 1 :
b_dup.append(x)
return a_dup, b_dup
result1, result2 = common(a,b)