如何解压缩从common()函数返回的两个列表(list1和list2)?

时间:2019-06-13 18:24:10

标签: python list

函数common()返回两个列表。我想将两个列表存储在两个不同的变量中(例如result1result2)。我该怎么办?

我尝试过,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)

1 个答案:

答案 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)