a = ['a','b','c']
b = ['w','y','z']
if a.sort() == b.sort():
print("True")
输出结果为“True”
想问一下对两个不相等列表使用sort.()排序之后为何会相等?
list.sort()原址排序方法,没有返回值。如果非要说有,那就是None
您的a.sort() = b.sort()操作,相当于None == None,您说会不会True?
您用新生成列表排序函数sorted()试试,看看还True不True?
代码
print('\n', sorted(a), sorted(b), sorted(a) == sorted(b), '\n')
代码运行效果截屏图片为证
python 代码
#!/sur/bin/nve python
# coding: utf-8
a = ['a','b','c']
b = ['w','y','z']
if a.sort() == b.sort():
print("True")
print(a.sort(), a.sort() is None)
print(b.sort(), b.sort() is None)
比较不是列表,而是sort的返回值
不知道你这个问题是否已经解决, 如果还没有解决的话:问题原因:
问题出在你对a和b使用了sort()函数。sort()函数是将列表原地排序,即在原来的列表上进行排序,并且返回值为None。所以当你比较a.sort()和b.sort()的结果时,实际上是在比较None和None,因此条件判断结果为True。
解决方案:
要解决这个问题,可以改变你的比较方式。可以先使用sort()对a和b进行排序,然后再直接比较排序后的列表。具体代码如下:
a = ['a', 'b', 'c']
b = ['w', 'y', 'z']
a.sort()
b.sort()
if a == b:
print("True")
这样就可以正确比较两个列表是否相等了。
另外,如果你不想改变原列表,可以使用sorted()函数对列表进行排序,它会返回一个新的排序后的列表,示例代码如下:
a = ['a', 'b', 'c']
b = ['w', 'y', 'z']
sorted_a = sorted(a)
sorted_b = sorted(b)
if sorted_a == sorted_b:
print("True")
这样也可以达到相同的效果。