列表中删除数据经常出现的两个问题
问题1: 通过元素删除的时候可能出现删不干净的问题
scores = [10, 50, 90, 89, 45, 70]
for score in scores:
if score < 60:
scores.remove(score)
print(scores, score) #[50,90,89,70]
程序执行过程分析:
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] 程序结束!
最终漏删50,且,元素70不会进入循环进行判断
问题解决:
思路:出现上面问题的根本原因是因为当scores列表中有元素满足条件被删除时,导致列表长度随之发生改变,导致for遍历出现问题,出现元素漏遍历,漏删的情况。
所以,我们要解决它,就需要一个和scores列表元素一样的新列表用于遍历,而执行删除过程却不会影响该新列表,故我们要声明一个新的列表,取值和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:通过下标删除满足要求的元素的时候,出现下标越界的错误
print('====================问题2=====================')
scores = [10, 50, 90, 89, 45, 70]
for index in range(len(scores)):
if scores[index] < 60:
del scores[index]
print(scores) #下标越界错误
问题解决:
思路:出现该问题的根本原因是,通过下标遍历删除元素时,列表长度减小,但是index仍在增加,这就注定遍历会出现下标(索引)越界。
因此,我们在删除一个元素后,要让index值不再增加,当没有删除时,index+,继续遍历。
程序如下:
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)