繁体   English   中英

比较两个列表会返回 True,即使它需要返回 False

[英]Comparing two lists returns True even though it needs to return False

我试图制作一个程序来比较两个列表,如果它们都具有相同的变量,则返回“True”,否则返回“False”。

代码是:

def are_lists_equall(list1, list2):
    if len(list1) == len(list2) and list1.sort() == list2.sort():
        return True
    else:
        return False

list1 = [0.6, 1, 2, 3]
list2 = [9, 0, 5, 10.5]
print(are_lists_equall(list1, list2))

输出是:

True

为什么?

它们的长度是 4,所以第一个是 true 并且 sort() 方法不返回任何值。 相反,它会更改原始列表。 就像是

if 4 == 4 and None == None:

这就是为什么它的真实和真实

如果要确保比较这些列表,请使用 sorted() 方法:

sorted(list1) == sorted(list2)会给你False

您好,欢迎来到堆栈溢出。

sort方法对列表本身进行排序并且不返回排序列表,实际上sort()返回 None。

所以长度相等并且 None == None -> 因此你得到True

你应该写:

   def are_lists_equall(list1, list2):


    if len(list1) == len(list2):
       list1.sort()
       list2.sort()
       if list1 == list2:
          return True
       else:
          return False
    else:
       return False
   
   list1 = [1, 2, 3, 4]
   list2 = [2, 1, 3, 4] 
   print(are_lists_equall(list1, list2))

我建议你也阅读这篇很棒的文章: https : //www.tutorialspoint.com/how-to-compare-two-lists-in-python

您应该使用两个列表的值创建临时变量,以便对它们进行排序和比较:

def are_lists_equall(list1, list2):
    l1 = list1
    l1.sort()
    l2 = list2
    l2.sort()
    
    if l1 == l2:
        return True
    else:
        return False

list1 = [0.6, 1, 2, 3]
list2 = [9, 0, 5, 10.5]
print(are_lists_equall(list1, list2))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM