Out*_*axy 0 python integer comparison-operators
我在下面有以下 Python 代码。我期待代码返回,True但是当我运行它时,它似乎总是返回False. 检查 361 是否为 361 时似乎失败,但我不知道为什么:
def comp(array1, array2):
if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
return False
aListSquared = [x * x for x in sorted(array1)]
array2.sort()
print(aListSquared)
print(array2)
for x in range(len(aListSquared)):
print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
print('{0}:{1}'.format(array2[x], type(array2[x])))
if int(aListSquared[x]) is not int(array2[x]):
return False
return True
a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么或者为什么验证似乎没有正常工作?
非常感谢
在你的行中
if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
Run Code Online (Sandbox Code Playgroud)
和
if int(aListSquared[x]) is not int(array2[x]):
Run Code Online (Sandbox Code Playgroud)
您正在使用is运算符来比较两个整数。这不是 Python 中应该如何使用运算符的方式:运算符用于测试对象身份,但您只想找出值是否相同。在您的情况下,您应该分别使用==代替is和!=代替is not。
如需进一步阅读,请参阅关于值比较和标识比较的 Python 文档,以及“is”运算符对整数的行为异常。