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
CodePudding user response:
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
CodePudding user response:
Assuming the indices to skip are few, why not create a new numpy array of zeros and fill the values from the original array like:
newgraph = np.zeros(graph2.shape, dtype=np.int8)
indices = [[0, 3], [3, 2], [2, 0]]
for i, j in indices:
newgraph[i,j] = graph2[i, j]
print(newgraph):
[[ 0 0 0 20]
[ 0 0 0 0]
[15 0 0 0]
[ 0 0 30 0]]