Python 中列表删除元素删不干净的问题

  • 现在已知一个分数列表:[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]
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值