嵌套循环在执行布尔矩阵乘法时更改多个值

时间:2019-07-15 10:03:40

标签: python matrix boolean matrix-multiplication

编写一个将两个矩阵(A,B)相乘并返回结果的函数。 A和B都是二维列表,并且具有相乘的兼容维度
我的代码将0和1转换为true和false,然后将它们相乘,然后再转换回去。

def matrix_multiply_boolean(A,B):
    #converts to boolean
    ra = len(A)
    ca = len(A[0])
    rb = len(B)
    cb = len(B[0])
    for i in range(ra):
        for z in range(ca):
           # print (A[i][z])
            if A[i][z]==0:
                A[i][z]=False
            if A[i][z]==1:
                A[i][z]=True
    for i in range(rb):
        for z in range(cb):
            print (B[i][z])
            if B[i][z]==0:
                B[i][z]=False
            if B[i][z]==1:
                B[i][z]=True

    #print(A)
    #print(B)
            #compares True and False vlaues
            #cant figure out why when the function cycles throught the first z #it sets two valeus to true

    new_list = [[True] * cb] * ra

    for z in range(ra):
        for i in range(cb): # *****on the second loop around the value of two #elements change and I have no idea why*****
            value = False 
            for j in range(ca):
                value = value or A[z][j] and B[j][i]
                print (value,j) #shows the value and how many times its been #throgh the loop.  goes 3 times 
            new_list[z][i] = value   #changes the value in the list
            print("newlist ",new_list[z][i]) # shows the value that was set #from line 59
            print(new_list) # shows you the list at the end of one whole #calculation

            #converts funtion back to boolean numbers
    rnl = len(new_list)
    cnl = len(new_list[0])
    for i in range(rnl):
        for z in range(cnl):
            #print (new_list[i][z])
            if new_list[i][z]==False:
                new_list[i][z]=0
            if new_list[i][z]==True:
                new_list[i][z]=1


    return new_list

A= [ [0,1,1],[1,0,0]]
B= [ [1,0],[0,0],[0,1]]
print(matrix_multiply_boolean(A,B))

乘法完成后,我获得了正确的布尔值,但设置不正确,因此我不知道为什么。发生的情况是在完成一行之后,它开始了新的一行,并且在下一个乘法完成时,它更改了[1,0](当前行)和[0,0](上一行在同一列)的值只有[1,0]。由于某种原因,这只会在循环的第一个元素上发生

期望值[[0,1],[1,0]]
实际值[[1,0],[1,0]]

1 个答案:

答案 0 :(得分:0)

更改

new_list = [[True] * cb] * ra

new_list = [[True for j in range(0, cb)] for i in range(0, ra)]

它会输出所需的结果。

new_list中存储的对象不仅是彼此的副本,而且实际上是相同的对象。对于您的示例(其中cb == 2ra == 2),new_list内部看起来像这样:

[[A, B], [A, B]]

其中AB均为值为True的布尔值。现在,当您更改A时,new_list会在两个位置更改,因为它们每个都引用相同的对象AB的情况也是如此。 new_list中存储的两个列表与您的代码始终相同。