题目:scores = [34, 78, 56, 55, 46, 89, 43, 34, 56, 78]
删除列表里小于60的数
常规做法:日常掉坑1
for score in scores:
if score < 60:
scores.remove(score)
print(scores) # [78, 55, 89, 34, 78]
掉坑分析:因为删除元素,导致遍历不完全导致的删除不干净
'''
代码分析:
scores = [34, 78, 56, 55, 46, 89, 43, 34, 56, 78]
0 score = 34; 34<60 --> scores = [78, 56, 55, 46, 89, 43, 34, 56, 78]
1 score = 56; 56<60 --> scores = [78, 55, 46, 89, 43, 34, 56, 78]
2 score = 46; 46<60 --> scores = [78, 55, 89, 43, 34, 56, 78]
3 score = 43; 43<60 --> scores = [78, 55, 89, 34, 56, 78]
4 score = 56; 56<60 --> scores = [78, 55, 89, 34, 78]
5 循环结束
综上分析:
遍历不到的数字有:78, 55,89, 34,78
'''
解题思路:保证遍历取值能够能够取完所有的值
正确代码:
scores = [34, 78, 56, 46, 89, 43, 34, 56, 78]
for score in scores[:]:
if score < 60:
scores.remove(score)
print(scores) # [78, 89, 78]
常规做法:日常掉坑2
scores = [34, 78, 56, 46, 89, 43, 34, 56, 78]
length = len(scores)
for index in range(length):
print(scores[index])
if scores[index] < 60:
del scores[index]
print(scores)
掉坑分析:
- 因为是遍历下标,在删除元素时会导致下标越界而报错;
- 同时也会因为删除元素,而导致遍历不完全;
'''
代码分析:
scores=[34, 78, 56, 46, 89, 43, 34, 56, 78]
length=len(scores) = 9
index=0 34<60 del scores[0]; scores=[78, 56, 46, 89, 43, 34, 56, 78]
index=1 56<60 del scores[1]; scores=[78, 46, 89, 43, 34, 56, 78]
index=2 89>60 scores=[78, 46, 89, 43, 34, 56, 78]
index=3 43>60 del scores[3]; scores=[78, 46, 89, 34, 56, 78]
index=4 56>60 del scores[4]; scores=[78, 46, 89, 34, 78]
index=5 报错(索引下标越界):IndexError: list index out of range
综上分析:
遍历不到的数字:78, 46,34,78
'''
解题思路:注意索引值的变化
正确代码:
scores = [34, 78, 56, 46, 89, 43, 34, 56, 78]
index = 0
while index < len(scores):
if scores[index] < 60:
del scores[index]
continue # 当遇到的值小于60时会被删除,我们直接停止本次循环,不让索引增加
# index -= 1 # 当遇到的值小于60时会被删除,我们先在本次循环让索引减1,外面在加1,索引不变
index += 1
print(scores)
网友评论