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

2024-04-20 06:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个函数,将两个矩阵(a,B)相乘并返回结果。A和B都是2d列表,并且具有兼容的乘法维数
我的代码将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]]


Tags: theinfalsetruenewforlenif
1条回答
网友
1楼 · 发布于 2024-04-20 06:24:18

改变

new_list = [[True] * cb] * ra

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

并输出期望的结果

存储在new_list中的对象不仅是彼此的副本,而且实际上是相同的对象。对于您的示例(其中cb == 2ra == 2new_list内部如下所示:

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

其中AB分别是值为True的布尔值。现在,当您更改Anew_list时,会在两个地方更改,因为它们分别引用相同的对象AB也是如此。存储在new_list中的两个列表与您的代码总是相同的

相关问题 更多 >