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

Python删除数字列表最后一个偶数代码返回None问题排查

代码问题分析
  • 判断条件逻辑错误
    你写的if len(num_list) % 2 == 0是判断列表的长度是否为偶数,和你要实现的「判断元素是否为偶数」的逻辑完全无关,不符合需求。
  • 返回值缺失
    你的代码仅在else分支写了return num_list,如果代码进入if分支,执行完num_list.pop()后没有任何返回语句,Python中函数没有显式return时会默认返回None,这就是你得到None的直接原因。
  • 核心功能逻辑错误
    你当前的逻辑哪怕修正了判断条件,也只能判断列表最后一个元素是不是偶数,而需求是删除列表中最后一次出现的偶数——哪怕列表末尾几个元素都是奇数,也要向前遍历找到最近的偶数删除。
修正后的实现代码
# Task_5
def delete_last_even(num_list):
    """Removes the last even number from a list of numbers.
    Args:
        num_list (list): List of numbers to be checked.
    Returns:
        list: List of numbers with the last even number
            removed.
    """
    # 倒序遍历列表,找到第一个偶数即原列表最后一个偶数
    for index in range(len(num_list) - 1, -1, -1):
        if num_list[index] % 2 == 0:
            num_list.pop(index)
            break
    # 所有分支统一返回处理后的列表
    return num_list

# 测试调用
print(delete_last_even([7, 65, 1337, 8, -2, 24, 6, 67, 54, 36, 25, 1, 42, 9, 138, 4356, 6]))

内容的提问来源于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:51:00