你是內環路返回,所以你只能有一個通過外循環:
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]
聽起來像你可能需要一個'while'循環。 – monkut 2014-10-22 01:26:50
雅我認爲是這樣,但我沒有我應該把這個循環放在這裏:而X,Y在郵編(水庫,猜): – Deka 2014-10-22 01:30:22