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

Python for循环无法删除列表所有奇数,代码哪里出错了?

问题原因

你遇到的是遍历列表的同时修改列表导致的索引错位问题:

  • for循环遍历列表时,本质是按索引依次取值。当你删除列表中某一个元素后,该元素后面的所有元素都会自动向前移动一个位置,导致下一次循环直接跳过了刚移动到当前索引位的元素。
  • 以你传入的参数为例:第一次循环取索引0的元素7,判断为奇数执行删除后,原索引1的65会前移到索引0的位置,下一轮循环会直接取索引1的元素,65就被跳过没有做奇偶判断,这也是你返回结果里还存在65、1这类奇数的原因。
修复方案

方案1:遍历原列表构建新列表(最推荐,逻辑清晰不易出错)

不要在正在遍历的列表上执行删除操作,直接筛选符合条件的元素存入新列表即可:

def delete_odd(num_list):
    """Removes all odd numbers from a list of numbers.

    Args:
        num_list (list): List of numbers to be checked.
    Returns:
        list: List of numbers with all odd numbers removed.
    """
    new_list = []
    for num in num_list:
        if num % 2 == 0:
            new_list.append(num)
    return new_list

方案2:用列表推导式简化代码

和方案1逻辑完全一致,写法更简洁:

def delete_odd(num_list):
    """Removes all odd numbers from a list of numbers.

    Args:
        num_list (list): List of numbers to be checked.
    Returns:
        list: List of numbers with all odd numbers removed.
    """
    return [num for num in num_list if num % 2 == 0]

方案3:倒序遍历删除(如果需要在拷贝的列表上操作)

如果一定要对拷贝的列表做删除操作,改为倒序遍历索引即可,删除元素不会影响还未遍历的前序索引:

def delete_odd(num_list):
    """Removes all odd numbers from a list of numbers.

    Args:
        num_list (list): List of numbers to be checked.
    Returns:
        list: List of numbers with all odd numbers removed.
    """
    new_list = list(num_list)
    for i in range(len(new_list)-1, -1, -1):
        if new_list[i] % 2 == 1:
            del new_list[i]
    return new_list

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:36:04