Home > Software engineering >  How do I replace elements in two-dimensional array in python?
How do I replace elements in two-dimensional array in python?

Time:05-10

My task is to replace all the elements whose both indexes are odd with 1, and all the elements whose both indexes are even with -1.

CodePudding user response:

You can replace elements by using a double index like: array[y][x] if array is list of lists.

This is a example:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
length = len(array)
for y in range(length):
    for x in range(length):
        if y % 2 and x % 2:
            array[y][x] = 1
        elif y % 2 == 0 and x % 2 == 0:
            array[y][x] = 0
print(array)

This will output: [[0, 2, 0], [4, 1, 6], [0, 8, 0]]

CodePudding user response:

Answer:

for i in range(row):
    for j in range(col):
        if (i%2==0 and j%2==0):
            array[i][j] = -1
        elif (i%2 and j%2):
            array[I][j] = 1

row => length of nested array

col => length of the array

CodePudding user response:

test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def replace(arr):
    for i in range(len(arr)):
        for j in range(len(arr)):
            if i % 2 and j % 2:   # checks if both indexes are odd
                test[i][j] = 1
            elif not i % 2 and not j % 2: # checks if both indexes are even
                test[i][j] = -1
    return arr

print(replace(test))  # [[-1, 2, -1], [4, 1, 6], [-1, 8, -1]]
  • Related