- 現(xiàn)在已知一個分?jǐn)?shù)列表:[89,45,55,30,78,90,34,87,10,59,100]凡怎,要求刪除列表中低于60的值
scores = [89,45,55,30,78,90,34,87,10,59,100]
scores.sort()
for cj in scores:
if cj<60:
scores.remove(cj)
print(scores) #[30, 45, 59, 78, 87, 89, 90, 100]
很明顯镣典,上面這種直接刪除的方法并沒有答到想要的效果。30和45并沒有被刪掉。
出現(xiàn)這種結(jié)果的原因是因?yàn)榱斜碓谶M(jìn)行遍歷的時候间景,當(dāng)刪除了第一個數(shù)10的時候,30占據(jù)了第一個數(shù)10的位置艺智,因此遍歷時并沒有對30這個數(shù)進(jìn)行判斷倘要,因而30沒有被刪掉。
同理可得力惯,34被刪掉后45這個數(shù)被跳躍了碗誉。
解決方法如下:
#方法一:對原列表進(jìn)行備份,遍歷時遍歷備份的列表父晶。
scores = [89,45,55,30,78,90,34,87,10,59,100]
new_scores = scores[:]
for score in new_scores:
if score<60:
scores.remove(score)
print(scores) # [89, 78, 90, 87, 100]
# 方法二:在刪除數(shù)據(jù)的時候使下標(biāo)不變
scores = [89,45,55,30,78,90,34,87,10,59,100]
index = 0
while index<len(scores):
if scores[index]<60:
del scores[index]
else:
index += 1
print(scores) # [89, 78, 90, 87, 100]