Python比较两个列表时返回预期外True而非False的原因是什么
问题根因
- Python列表的
sort()方法为原地排序接口,仅修改原列表的元素顺序,返回值固定为None - 你代码中
list1.sort() == list2.sort()的本质是两个None值做相等判断,结果永远为True - 你的测试用例中两个列表长度均为4,因此
len(list1) == len(list2)也为True,整个判断条件成立,最终错误返回True
修复方案
替换sort()方法为sorted()内置函数即可:sorted()会返回排序后的新列表,不会修改原列表,排序后的列表直接比较就能判断元素是否完全一致(包含元素出现次数校验)。
修复后的代码示例:
def are_lists_equal(list1, list2): if len(list1) == len(list2) and sorted(list1) == sorted(list2): return True else: return False # 也可以简化为直接返回布尔表达式,效果完全一致 # def are_lists_equal(list1, list2): # return len(list1) == len(list2) and sorted(list1) == sorted(list2) list1 = [0.6, 1, 2, 3] list2 = [9, 0, 5, 10.5] print(are_lists_equal(list1, list2)) # 输出False,符合预期
内容的提问来源于stack exchange,提问作者user16713791
相关产品推荐
相关产品推荐

