Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace all the value except for the one a specified index of a numpy matrix with zero

I have the following array

graph2 = [[0, 10, 15, 20],
        [10, 0, 35, 25],
        [15, 35, 0, 30],
        [20, 25, 30, 0]]

I want to replace all to zero except for values at a specific index.
Like Index (1,4), so the 20 at first line i don’t place zero
(4,3) the 30 at fourth list, and (3,1) the 15 in third list

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Remember that list index Starts at 1 not at 0. So your list indexes are wrong. I fixed them below

graph2 = [[0, 10, 15, 20],
        [10, 0, 35, 25],
        [15, 35, 0, 30],
        [20, 25, 30, 0]]
skip = [(0, 3), (3, 2), (2,0)]
for i in range(len(graph2)):
    for j in range(len(graph2[i])):
        if (i, j) in skip:
            continue
        else:
            graph2[i][j] = 0
print(graph2)

This should work

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading