- 现在已知一个分数列表:[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并没有被删掉。
出现这种结果的原因是因为列表在进行遍历的时候,当删除了第一个数10的时候,30占据了第一个数10的位置,因此遍历时并没有对30这个数进行判断,因而30没有被删掉。
同理可得,34被删掉后45这个数被跳跃了。
解决方法如下:
#方法一:对原列表进行备份,遍历时遍历备份的列表。
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]
# 方法二:在删除数据的时候使下标不变
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]
# 不增加额外计算空间删除重复元素
nums = [1,1,2,3,4,5,5]
index = 0
while index < len(nums):
num = nums.pop(index)
if num in nums:
index += 1
else:
nums.append(num)
index +=1
print(nums) # [1, 3, 5, 2, 4]