Python:替换Matrix的多个值

时间:2015-03-06 12:23:58

标签: python python-3.x matrix

我有这个矩阵:

M = [[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]]

我想用x替换M [1] [2]到M [2] [3]的值 所以矩阵看起来像这样:

[[0, 0, 1, 0], [1, 0, "x", "x"], ["x", "x", "x", "x"], [0, 1, 0, 0]]

2 个答案:

答案 0 :(得分:2)

M = [[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 5, 1], [0, 1, 0, 0]]
x=1

while (x<=2):
    if (x==1):
        y=2
    else:
        y=0
    while (y<=3):
        M[x][y]="x"
        y+=1
    x+=1

输出:

[[0, 0, 1, 0], [1, 0, "x", "x"], ["x", "x", "x", "x"], [0, 1, 0, 0]]

答案 1 :(得分:1)

startIndexX = 1
startIndexY = 2
endIndexX = 2
endIndexY = 3

x = startIndexX
firstLoop = True
while (x<=startIndexY):
    y=endIndexX
    if(not firstLoop):
        y=0
    while (y<=endIndexY):
        M[x][y]="x"
        y+=1
    x+=1
    firstLoop = False

<强>输出

[[0, 0, 1, 0], [1, 0, 'x', 'x'], ['x', 'x', 'x', 'x'], [0, 1, 0, 0]]