如何替换python中二维数组中的元素?

How do I replace elements in two-dimensional array in python?

我的任务是将所有索引为奇数的元素替换为1,将所有索引为偶数的元素替换为-1。

答案:

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

行 => 嵌套数组的长度

col => 数组的长度

您可以使用双索引替换元素,例如:array[y][x] 如果 array 是列表的列表。

这是一个例子:

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)

这将输出:[[0, 2, 0], [4, 1, 6], [0, 8, 0]]

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]]