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

Python编写Advent of Code脚本时For循环未遍历列表全部元素怎么办

问题原因
  • 遍历列表过程中删除列表元素会触发索引错位:你初始的current_list长度为4,当你遍历到下标为2的元素"1111"时触发删除操作,列表长度会立即变为3,原下标为3的元素"0011"会自动前移到下标2的位置,等循环要读取下标3的元素时,列表已经不存在该下标,因此会少遍历1个元素。
  • oxygen_list = current_list属于引用赋值,两个变量指向同一个列表对象,修改oxygen_list等价于直接修改current_list,这也是你最终打印current_list发现内容变化的原因。
修复方案

有两种常用的修改方案,都可以避免索引错位问题:

方案1:遍历列表副本,修改原列表

遍历列表的浅拷贝对象,遍历过程不受原列表修改影响:

def count(data, target_bit):
    zero_count = 0
    one_count = 0
    for numbers in data:
        if numbers[target_bit] == '0':
            zero_count += 1
        else:
            one_count += 1
    return [zero_count, one_count]

current_list = ["1001", "0001", "1111", "0011"]
# 改为浅拷贝,两个列表独立
oxygen_list = current_list.copy()
current_index = 1

zero_count = count(current_list, current_index)[0]
one_count = count(current_list, current_index)[1]

if zero_count > one_count:
    loop_count = 0
    # 遍历原列表的副本
    for items in current_list.copy():
        print(loop_count)
        if items[current_index] == "1":
            oxygen_list.remove(items)
        loop_count += 1
        

print(oxygen_list)

方案2:用列表推导式直接生成新列表

这种写法更简洁高效,完全规避遍历过程中修改列表的问题:

if zero_count > one_count:
    oxygen_list = [item for item in current_list if item[current_index] != "1"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:15:01