numpy 不知何故,if语句中的代码即使在条件为false时也会运行

bqucvtff  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(69)

这里有一个函数:

def check_similarity(bit_pos_array):
    for i, bit_pos in enumerate(bit_pos_array):
        for j, other_bit_pos in enumerate(bit_pos_array):
            if i == j:
                continue
            not_similar = (False in (bit_pos == other_bit_pos))
            if not not_similar:
                print('not_similar : ',not_similar)
                raise Exception('holy crap they are the same', i, ' ', j)
    return False

字符串
它的输入是一个2D numpy浮点数组,如果没有一个数组彼此相似(在完全相同的索引中具有完全相同的值),则应该返回False,如果找到任何相似的数组,则引发Exception。当我在if语句中添加断点时,'not_similar'为True(有效),但其中的代码仍在运行,会引发异常,但不会执行print语句。如果内部没有断点,则执行print语句,打印的值为False(无效),并引发异常。是什么导致了这种奇怪的行为?
我试图从enumerate切换到range,并扰乱循环的内容,但我总是得到这种奇怪的行为。
在调试时,我可以看到,即使在引发异常时,数组中的值实际上也不相同

v1l68za4

v1l68za41#

你在这里检查了一个双重否定的场景,这影响了你的逻辑。

not_similar = (False in (bit_pos == other_bit_pos))
if not not_similar

字符串
如果数字匹配,第一行将返回True,而对于不同的值,它将产生False,那么条件是当数字应该匹配,但not True使其成为False时,这导致它在数字匹配时跳过,但在不匹配时运行。
更新了你的代码来修复这个条件,并优化了你的循环:

def check_similarity(bit_pos_array):
    for i, bit_pos in enumerate(bit_pos_array):
        print(bit_pos_array, bit_pos_array[i+1:])
        for j, other_bit_pos in enumerate(bit_pos_array[i+1:]):
            if bit_pos == other_bit_pos:
                print('Similar : ', True)
                raise Exception(f'holy crap they are the same at {i} and {j+i+1}, with number {bit_pos}')
    
    return False

print(check_similarity([1, 2, 3, 1]))


输出量:

Exception: holy crap they are the same at 0 and 3, with number 1

相关问题