今天在学习删除列表元素的时候,发现这两种方式结果不一样:
第一种:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
for i in pets:
if i == 'dog':
pets.remove(i)
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
输出结果为:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['cat', 'goldfish', 'cat', 'rabbit', 'cat']
['goldfish', 'rabbit']
第二种是将for循环与while循环置换了一下位置:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
for i in pets:
if i == 'dog':
pets.remove(i)
print(pets)
输出结果为:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
['dog', 'goldfish', 'rabbit']
然而这种情况下,for循环没有将列表中的dog删完,因此感到很困惑。
希望各位大神能帮我解除疑惑。