You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表去重异常求助:为何结果是[2,3,3]而非预期[2,3]

Python列表循环去重异常原因解析

你的判断完全正确——循环过程中修改列表导致迭代错位,就是结果不符合预期的根源。我们一步步拆解代码执行过程,就能看明白问题出在哪:

首先看你的代码:

list = [2,2,3,3]
duplicate = 0
for numbers in list:
    if duplicate == numbers:
        list.remove(numbers)
    else:
        duplicate = numbers
print(f'List after duplicates removed {list}')

执行步骤拆解

  1. 初始状态:列表是[2,2,3,3],duplicate=0,迭代器准备依次遍历列表的4个元素(索引0到3)。
  2. 第一次循环:取索引0的元素2,0≠2,所以duplicate更新为2,列表不变。
  3. 第二次循环:取索引1的元素2,2=2,执行list.remove(2)——此时列表被修改为[2,3,3](长度从4变成3)。
  4. 关键问题出现:Python的for循环依赖列表的迭代器,迭代器只会记录当前遍历的位置。原本迭代器走到了索引1,现在列表变短,下一次循环会直接取索引2的元素,但此时列表的索引2是3,而原本索引1的新元素(也就是第二个3)被跳过了。
  5. 第三次循环:取索引2的元素3,2≠3,duplicate更新为3,列表不变。
  6. 迭代器已经遍历完原来的4个位置,循环结束,最终列表就是[2,3,3]。

修复方案

方案1:遍历列表的副本

这样修改原列表时,循环不受影响:

my_list = [2,2,3,3]  # 别用list当变量名,会覆盖内置类型
duplicate = 0
for numbers in my_list.copy():  # 遍历副本
    if duplicate == numbers:
        my_list.remove(numbers)
    else:
        duplicate = numbers
print(f'List after duplicates removed {my_list}')

方案2:生成新列表(更安全高效)

避免在循环中修改原列表,直接构建去重后的新列表:

my_list = [2,2,3,3]
new_list = []
for num in my_list:
    if not new_list or num != new_list[-1]:
        new_list.append(num)
print(new_list)  # 输出[2,3]

内容的提问来源于stack exchange,提问作者Gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:00:47