将值添加到矩阵的下一行
adding values to the next row of matrix
我有一个矩阵 (5,5) #empty matrix
我想按行添加元素。
如果上一行已满,如何编写代码将元素添加到下一行。
第一行已满,我想添加更多元素,但自动从下一行开始
这可能是您想要的:
outer_matrix = [[None]*5 for i in range(5)]
def auto_add(element, matrix):
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if matrix[row][col] == None:
# There is a free space, add element to it
matrix[row][col] = element
return matrix
for i in range(12):
outer_matrix = auto_add(i, outer_matrix)
>>> outer_matrix
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
如果您总是使用 5 x 5
矩阵,这会更干净:
for row in range(5):
for col in range(5):
我有一个矩阵 (5,5) #empty matrix 我想按行添加元素。
如果上一行已满,如何编写代码将元素添加到下一行。
第一行已满,我想添加更多元素,但自动从下一行开始
这可能是您想要的:
outer_matrix = [[None]*5 for i in range(5)]
def auto_add(element, matrix):
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if matrix[row][col] == None:
# There is a free space, add element to it
matrix[row][col] = element
return matrix
for i in range(12):
outer_matrix = auto_add(i, outer_matrix)
>>> outer_matrix
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
如果您总是使用 5 x 5
矩阵,这会更干净:
for row in range(5):
for col in range(5):