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
相关产品推荐
相关产品推荐

