我有一個矩陣 (5,5) #empty 矩陣,我想逐行添加元素。
如果上一行已滿,如何編碼以將元素添加到下一行。
第一行已滿,我想添加更多元素,但自動從下一行添加
uj5u.com熱心網友回復:
這可能是你所追求的:
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):
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461731.html
