Python contains函数空列表测试用例无法通过,寻求问题排查
问题分析与解决
你的判断不对,问题根本不是“判断空列表的语句未关联目标”,而是代码里存在几个关键逻辑错误:
核心问题点
- 空列表时循环不执行:当
some_list是空列表,len(some_list)为0,range(0)生成的是空序列,for循环直接跳过,函数里的三个if语句都不会执行,函数默认返回None,而你的断言期望返回False,自然不匹配。 - for循环完全冗余:你在循环里直接用
target in some_list,这个操作本身已经会遍历整个列表判断存在性,外层的for循环完全没必要。 - 判断顺序错误:空列表的判断放在循环内部,永远不会被执行到,应该放在函数最开头优先处理。
修正后的代码
def contains(some_list: list[int], target: int) -> bool: # 优先处理空列表情况,直接返回False if not some_list: return False # 直接返回判断结果,无需多余循环和分支 return target in some_list # 测试用例保持不变 assert contains([1, 5, 2, 6, 9, 0], 5)==True, "5 is in the list" assert contains([1, 10, 2, 6, 9, 0], 5)==False, "5 is not in the list" assert contains([5, 1, 2, 6, 9], 5)==True, "5 is in the list" assert contains([1, 2, 6, 9, 5], 5)==True, "5 is in the list" assert contains([], 5)==False, "5 is not in an empty list" print("All tests passed!")
最简版优化
其实空列表的判断可以直接省略,因为target in []本身就会返回False,最简函数写法如下,同样能通过所有测试:
def contains(some_list: list[int], target: int) -> bool: return target in some_list
内容的提问来源于stack exchange,提问作者internet joe
相关产品推荐
相关产品推荐

