Python代码在应为true时验证False。为什么会这样?

问题描述 投票:-1回答:1

我在下面有以下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))

有人可以告诉我我做错了什么,或者为什么验证似乎无法正常工作吗?

非常感谢

python pycharm
1个回答
1
投票

在您的行中

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运算符比较两个整数。

解决方案:改用==

请参见"is" operator behaves unexpectedly with integers以获取更多阅读。

© www.soinside.com 2019 - 2024. All rights reserved.