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)))
我需要输出为(1, 2, 5, 6)
,我的输出为(1, 2, 4, 4, 5, 6)
。
我无法找到我的错误。谁能帮帮我吗?
谢谢
答案 0 :(得分: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)))
答案 1 :(得分: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)