问题:通过元素删除的时候可能出现删不干净的问题
scores = [10,50,90,89,45,70]
for score in scores:
if score < 60:
scores.remove(score)
print(scores) # [50, 90, 89, 70]
解决问题:
scores = [10,50,90,89,45,70]
scores2 = scores[:]
for score in scores2:
if score < 60:
scores.remove(score)
del scores2 # score2只是提供遍历用的,用完后没有其他用处,可以直接删除
print(scores)
简写:
scores = [10,50,90,89,45,70]
for score in scores[:]:
if score < 60:
scores.remove(score)
print(scores)
下标问题 : 通过下标删除满足要求的元素的时候,出现下标越界的错误
scores = [10,50,90,89,45,70]
for index in range(len(scores)):
if scores[index] < 60:
del scores[index]
print(scores)
解决问题:
scores = [10,50,90,89,45,70]
index = 0
while index < len(scores):
if scores[index] < 60:
del scores[index]
else:
index+=1
print(scores)