Python 如何让函数在条件不充分时执行
基本上,我有一个函数,可以从第二个列表中的一个列表中删除所有字符,但我的函数似乎只删除列表中的第一个值。感谢您提供的任何帮助您将返回到回路内部,因此您只有一次通过外部回路:Python 如何让函数在条件不充分时执行,python,for-loop,Python,For Loop,基本上,我有一个函数,可以从第二个列表中的一个列表中删除所有字符,但我的函数似乎只删除列表中的第一个值。感谢您提供的任何帮助您将返回到回路内部,因此您只有一次通过外部回路: import copy def remove_fully_correct(answer, guess): """(list,list) -> list Return a list that removes the chars from the first list that a
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
如果列表大小相同,则应使用enumerate:
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
使用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 [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']
听起来你可能需要一个while循环。是的,我想是的,但我不知道应该把循环放在哪里:当x,y在zipres中时,猜猜:然后它说索引超出了范围
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]