0
def removeCommonElements(tup1,tup2):
count=0
lis1=list(tup1)
lis2=list(tup2)
while count<=len(lis1):
    for i in lis1:
        if i in lis2:
            lis1.remove(i)
            lis2.remove(i)
    count+=1
    return tuple(lis1+lis2)

print(removeCommonElements((1,2,3,4), (3,4,5,6)))

我需要输出 as(1, 2, 5, 6)并且我得到输出 as (1, 2, 4, 4, 5, 6)。我找不到我的错误。谁能帮帮我吗?谢谢

4

2 回答 2

2

就是缩进。缩进如下:

def removeCommonElements(tup1,tup2):
    count=0
    lis1=list(tup1)
    lis2=list(tup2)
    while count<=len(lis1):
        for i in lis1:
            if i in lis2:
                lis1.remove(i)
                lis2.remove(i)
        count+=1
    return tuple(lis1+lis2)

print(removeCommonElements((1,2,3,4), (3,4,5,6)))
于 2013-08-07T00:18:13.620 回答
1
for i in lis1:
        if i in lis2:
            lis1.remove(i)
            lis2.remove(i)

您的这部分代码正在遍历一个列表,同时修改它。所以 4 被排除在外。您可以使用 set 来执行此操作:

>>> def removeCommon(x, y):
...     x = set(x)
...     y = set(y)
...     return tuple(set.union(x, y)-set.intersection(x, y))
... 
>>> a = (1,2,3,4)
>>> b = (3,4,5,6)
>>> removeCommon(a, b)
(1, 2, 5, 6)
于 2013-08-07T00:37:59.737 回答