列表中刪除數(shù)據(jù)經(jīng)常出現(xiàn)的兩個問題
問題1: 通過元素刪除的時候可能出現(xiàn)刪不干凈的問題
scores = [10, 50, 90, 89, 45, 70]
for score in scores:
if score < 60:
scores.remove(score)
print(scores, score) #[50,90,89,70]
程序執(zhí)行過程分析:
scores = [10, 50, 90, 89, 45, 70] for 10 in scores if 10<60(True) scores=[50,90,89,45,70]
scores=[50,90,89,45,70] for 90 in scores if 90 < 60(F) scores=[50,90,89,45,70]
scores=[50,90,89,45,70] for 89 in scores if 89<60(F) scores=[50,90,89,45,70]
scores=[50,90,89,45,70],for 45 in scores if 45<60(T) scores=[50,90,89,70]
scores=[50,90,89,70] 程序結(jié)束!
最終漏刪50,且,元素70不會進(jìn)入循環(huán)進(jìn)行判斷
問題解決:
思路:出現(xiàn)上面問題的根本原因是因為當(dāng)scores列表中有元素滿足條件被刪除時,導(dǎo)致列表長度隨之發(fā)生改變,導(dǎo)致for遍歷出現(xiàn)問題,出現(xiàn)元素漏遍歷,漏刪的情況。
所以,我們要解決它,就需要一個和scores列表元素一樣的新列表用于遍歷,而執(zhí)行刪除過程卻不會影響該新列表,故我們要聲明一個新的列表,取值和scores一樣,地址不一樣。這里提供兩種方法:
- list2=scores[:]
- list2=scores.copy()
整個程序代碼如下:
scores = [10, 50, 90, 89, 45, 70]
scores2 = scores[:]
for score in scores2:
if score < 60:
scores.remove(score)
del scores2 # score2只是提供遍歷用的,用完后沒有其他用處,可以直接刪除
print(scores, score)
問題2:通過下標(biāo)刪除滿足要求的元素的時候,出現(xiàn)下標(biāo)越界的錯誤
print('====================問題2=====================')
scores = [10, 50, 90, 89, 45, 70]
for index in range(len(scores)):
if scores[index] < 60:
del scores[index]
print(scores) #下標(biāo)越界錯誤
問題解決:
思路:出現(xiàn)該問題的根本原因是,通過下標(biāo)遍歷刪除元素時,列表長度減小,但是index仍在增加,這就注定遍歷會出現(xiàn)下標(biāo)(索引)越界。
因此,我們在刪除一個元素后,要讓index值不再增加,當(dāng)沒有刪除時,index+,繼續(xù)遍歷。
程序如下:
scores = [10, 50, 90, 89, 45, 70]
index = 0
while index < len(scores):
if scores[index] < 60:
del scores[index]
continue
index += 1
print(scores)