遍历位于不同索引位置的元素

时间:2018-11-14 01:08:23

标签: python python-3.x python-2.7

我正在尝试制作一个从整数输入中打印网格的程序。

def grids(units):
    natural_number = int(input())
    # define size
    x = y = units

    # create empty rows
    grid = []

    # for each row defined by Y, append a list containing X occurrences of "."
    for row in range(y):
        grid.append(list("." * x))

    # fills the first row with natural_number
    for elements in range(units):
        grid[0][elements] = natural_number

    # fills the first column of each row with natural_number
    for elements in range(units):
        grid[elements][0] = natural_number

    return grid

    >>> grids(3)
    >? 5
    [[5, 5, 5], [5, '.', '.'], [5, '.', '.']]

对于grid [1] [1],grid [1] [2],grid [2] [1]和grid [2] [2]中的空位置

我的目标是输出以下数据

''''
    grid[1][1] = grid[1][0] + grid[0][1]
    grid[1][2] = grid[1][1] + grid[0][2]
    grid[2][1] = grid[2][0] + grid[1][1]
    grid[2][2] = grid[2][1] + grid[1][2]

    grid[i][j] = grid[i][j-1] + grid[i-1][j]
''''

要填补这些职位,我想出了以下代码。

但是,代码返回错误:int对象不可迭代。

该代码似乎还会引发一个问题,即它不会为grid [1] [2]或grid [2] [1]进行迭代

for i, j in range(1, units):
    grid[i][j] = grid[i][j - 1] + grid[i - 1][j]
return grid

我可以采取哪些措施来解决此问题?

1 个答案:

答案 0 :(得分:0)

如果你服用

for i, j in range(1,3):

并用

替换
for i in range(1, 3):
    for j in range(1, 3):

我认为这可以解决您的问题