问题
def delete_starting_evens(lst):
for i in lst:
if i%2==0:
lst.remove(i)
else:
break
return lst
The given code produces unexpected results, but I'm not able to figure out from the output where the problem lies.
回答1:
That's because you're suppressing items of a list your for-loop is iterating on. Hence it suppresses half of your items. For instance if you call your function on list [2, 2, 4, 6, 1]
it will delete the first 2 of your list then move to lst[1]
which is 4 (after deletion of the first 2), delete this one then move to lst[2]
which is now 1 and terminates. The resulting list will be [2, 6, 1]
It is very bad practice to modify the structure you are iterating on. Here you should prefer a while
loop:
def delete_starting_evens(lst):
while len(lst) > 0 and lst[0]%2==0:
lst.remove(lst[0])
return lst
l = [2, 2, 4, 6, 1]
delete_starting_evens(l)
print(l)
来源:https://stackoverflow.com/questions/63193121/why-does-my-code-for-removing-the-even-numbers-from-the-beginning-of-a-list-not