2014-10-22 14 views
1
import copy  
def remove_fully_correct(answer, guess): 
     """(list,list) -> list 
     Return a list that removes the chars from the first list that are the same and in the same position in the second list 
     >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d']) 
     ['a','c'] 
     """ 
     res = copy.copy(answer) 
     for index in range(len(res)): 
      for x, y in zip(res, guess): 
       if res[index] == guess[index]: 
        res.remove(x) 
       return res 

基本上我有一個功能,刪除所有從一個列表在第二列表中找到的人物,但我的功能似乎只刪除第一個值從列表中找到。任何幫助表示讚賞如何獲得一個函數來執行,直到條件不充分

+1

聽起來像你可能需要一個'while'循環。 – monkut 2014-10-22 01:26:50

+0

雅我認爲是這樣,但我沒有我應該把這個循環放在這裏:而X,Y在郵編(水庫,猜): – Deka 2014-10-22 01:30:22

回答

0

你是內環路返回,所以你只能有一個通過外循環:

import copy  
def remove_fully_correct(answer, guess): 
     """(list,list) -> list 
     Return a list that removes the chars from the first list that are the same and in the same position in the second list 
     >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d']) 
     ['a','c'] 
     """ 
     res = copy.copy(answer) 
     for index in range(len(res)): 
      for x, y in zip(res, guess): 
       if res[index] == guess[index]: 
        res.remove(x) 
     return res # move outside 

您應該使用枚舉,如果列表大小都一樣:

def remove_fully_correct(answer, guess): 
     """(list,list) -> list 
     Return a list that removes the chars from the first list that are the same and in the same position in the second list 
     >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d']) 
     ['a','c'] 
     """ 
     return [ele for index,ele in enumerate(answer) if ele != guess[index]] 


In [6]: remove_fully_correct(['a','b','c','d'], ['d','b','a','d']) 
Out[6]: ['a', 'c'] 

使用zip:

def remove_fully_correct(answer, guess): 
     """(list,list) -> list 
     Return a list that removes the chars from the first list that are the same and in the same position in the second list 
     >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d']) 
     ['a','c'] 
     """ 
     return [a for a,b in zip(answer,guess) if a != b] 
+0

然後說,索引超出範圍 – Deka 2014-10-22 01:34:00

+0

哦,其實我知道了 – Deka 2014-10-22 01:35:27

+0

感謝幫幫我! – Deka 2014-10-22 01:36:01

相關問題