2012-08-12 73 views
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))) 

我需要輸出爲(1, 2, 5, 6),我得到的輸出爲(1, 2, 4, 4, 5, 6)。 我無法找到我的錯誤。誰能幫幫我嗎? 謝謝Pyschools刪除常見元素

回答

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))) 
+0

純粹的諷刺...哈哈,虐待編輯它。 – enginefree 2013-08-07 00:21:56

+0

我認爲縮進只是OP的一個錯字。錯誤不在於此。 – zhangyangyu 2013-08-07 00:40:05

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)