增加2d数组的值?

时间:2013-11-21 06:54:31

标签: python arrays list

我正在尝试为我正在制作的游戏增加2d数组中的值,但我在每个数组中得到相同的值。这是代码:

def matrix(grid):

    nrows = len(grid)
    ncols = len(grid[0])

    for i in range(nrows):
        for j in range(ncols):
            grid[i][j] += 10

    for row in grid:
        print(row)

rows = 4
cols = 4
grid = [[0 for i in range(cols)] for i in range(rows)]
matrix(grid)

输出结果为:

[10, 10, 10, 10]
[10, 10, 10, 10]
[10, 10, 10, 10]
[10, 10, 10, 10]

我希望它在哪里

[10, 20, 30, 40]
[10, 20, 30, 40]
[10, 20, 30, 40]
[10, 20, 30, 40]

此外,是否可以交错并使用两个嵌套的for循环来为每一行提供递增的值?如:

[10, 20, 30, 40]
[20, 40, 60, 80]
[10, 20, 30, 40]
[20, 40, 60, 80]

5 个答案:

答案 0 :(得分:5)

输出符合预期:以下代码行为每个单元格添加10,并且由于每个单元格在输入时为零,因此在输出中变为10

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10

根据你想要做的事情,可能会做以下事情

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10*(j+1)

对于双循环版本(不是你提供的输出,但我没有找到模式)

for i in range(nrows):
    for j in range(ncols):
        grid[i][j] += 10*(i+j+1)

答案 1 :(得分:1)

你可以尝试这个循环:

for i in range(nrows):
    for j in range(ncols):
        if (i % 2 != 0):
            grid[i][j] += 20*(j+1)
        else:
            grid[i][j] += 10*(j+1)

输出:

[10, 20, 30, 40]
[20, 40, 60, 80]
[10, 20, 30, 40]
[20, 40, 60, 80]

答案 2 :(得分:1)

每当您必须修改整个列表时,请尝试使用理解来执行此操作。它很有效率。所以,你的问题可以通过这样的list comprehensions来解决

rows = 4
cols = 4
grid = [[0] * cols for _ in range(rows)]
print [[(i * 10) for i in xrange(1, len(row) + 1)] for row in grid]

<强>输出

[[10, 20, 30, 40], [10, 20, 30, 40], [10, 20, 30, 40], [10, 20, 30, 40]]

答案 3 :(得分:0)

您需要将代码更改为:

for i in range(nrows):
    val = 10
    for j in range(ncols):            
        grid[i][j] = val
        val += 10

答案 4 :(得分:0)

def matrix(grid):

nrows = len(grid)
ncols = len(grid[0])
grid[0][0]=10;
for i in range(nrows):
    for j in range(ncols):
if(j!=0)
      grid[i][j] = grid[i][j-1]+10;
else 
grid[i][j]=10;

for row in grid:
    print(row)