Ygon's Day07_刪除列表元素時,容易出現(xiàn)的兩個問題及解決方法

列表中刪除數(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一樣,地址不一樣。這里提供兩種方法:

  1. list2=scores[:]
  2. 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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容