我使用以下代码生成二维列表。
grid = [[ 1 if i == 0 or j == 0 else 0 for i in range(size) ] for j in range(size)]
生成
[1, 1, 1]
[1, 0, 0]
[1, 0, 0]
是否可以使用这些值来获取list comp中的下一个值,如
grid[1][1] = grid[0][1] + grid[1][0]
所以它看起来像
[1, 1, 1]
[1, 2, 3]
[1, 3, 6]
我知道我可以迭代它并获得结果,但是列表理解是否可能?
答案 0 :(得分:0)
这样看起来更容易以迭代的方式完成:
size = 5
grid = [[1 for i in range(size)] for j in range(size)]
for i in range(1, size):
for j in range(1, size):
grid[i][j] = grid[i-1][j] + grid[i][j-1]
print grid
结果(手动添加的间距):
[
[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]
]