python list 完全相等的坑:元素顺序不同判定为不相等

list1 = ["one","two","three"]
list2 = ["one","two","three"]
print(list1 == list2) # True
list1 = ["one","three","two"]
list2 = ["one","two","three"]
print(list1 == list2) # False 

解决办法

list1 = ["one","two","three"]
list2 = ["one","three","two"]
list1.sort()
list2.sort() # 改变list本身
print(list1 == list2)
list1 = ["one","two","three"]
list2 = ["one","three","two"]
list1 = sorted(list1)
list2 = sorted(list2) # 不改变list本身
print(list1 == list2)

猜你喜欢

转载自blog.csdn.net/weixin_41951954/article/details/130005698