假设我们有一个宠物列表,里面存放了一些宠物的名称,现在需要删掉当中的所有cat,我们可以使用while+in+remove的组合拳来完成这个任务。
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
pet_to_remove = 'cat'
while pet_to_remove in pets:
pets.remove(pet_to_remove)
print(pets)
删除前后的pets列表内容如下:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
[Finished in 0.7s]