在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()发布于 2015-12-05 23:24:30
您只需删除数组元素del tempArray[:],并且由于列表是可变的,它也清除了matrix的一部分
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)
tempArray = [] #del tempArray[:]
else:
tempArray.append(val)
print(matrix)
proj11_1_a()可以进一步简化/清除为
def proj11_1_a():
# Using eval in such place does not seem a good idea
# unless you want to accept things like "2*4-2"
# You might also consider putting try: here to check for correctness
n = int(input("Enter the size of the square matrix: "))
matrix = []
for _ in range(n):
row = []
for _ in range(n):
# same situation as with n
value = float(input("Enter a value to go into the matrix: "))
row.append(value)
matrix.append(row)
return matrix发布于 2015-12-05 23:32:40
另一种解决方案是更改以下行:
matrix.append(tempArray)至:
matrix.append(tempArray.copy())https://stackoverflow.com/questions/34112104
复制相似问题