我在下面有以下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))
任何人都可以告诉我我在做错什么,或者为什么验证似乎无法正常工作吗?
非常感谢
答案 0 :(得分:5)
在您的行中
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):
和
if int(aListSquared[x]) is not int(array2[x]):
您正在使用is
运算符比较两个整数。那不是在Python中使用运算符的方式:运算符用于测试对象标识,但是您只想确定值是否相同。对于您的情况,应该分别使用==
代替is
和!=
代替is not
。
有关更多信息,请参见Value comparisons和Identity comparisons上的Python文档,例如"is" operator behaves unexpectedly with integers。
答案 1 :(得分:2)
此语法
if int(aListSquared[x]) is not int(array2[x]):
与
不同if int(aListSquared[x]) != int(array2[x]):
答案 2 :(得分:1)
重写此表达式:
如果int(aListSquared [x])不是int(array2 [x]): 返回False
与此:
如果int(aListSquared [x])!= int(array2 [x]): 返回False
代码返回True。