在Python中,可以使用嵌套列表创建矩阵。例如,[[1, 2], [3, 4]]。下面我编写了一个函数,提示用户输入方阵的尺寸,然后在for循环中提示用户输入值。我有一个tempArray变量,它临时存储一行值,然后在附加到矩阵数组后被删除。但不知何故,在最后打印矩阵时,我得到的是这样的:[ [ ], [ ] ]。出了什么问题?
def proj11_1_a():
n = eval(input("Enter the size of the square matrix: "))
matrix = []
tempArray = []
for i in range(1, (n**2) + 1):
val = eval(input("Enter a value to go into the matrix: "))
if i % n == 0:
tempArray.append(val)
matrix.append(tempArray)
del tempArray[:]
else:
tempArray.append(val)
print(matrix)
proj11_1_a()
del tempArray[:]
- lejlot