使用Python创建矩阵
在Python中,可以使用嵌套列表创建矩阵。例如,[[1,2],[3,4]]。下面我编写了一个函数,提示用户输入方阵的尺寸,然后提示用户输入for循环中的值。我有一个tempArray变量,它临时存储一行值,然后在附加到矩阵数组后被删除。出于某种原因,当我在最后打印矩阵时,得到的结果是:[[],[]。出什么事了使用Python创建矩阵,python,matrix,Python,Matrix,在Python中,可以使用嵌套列表创建矩阵。例如,[[1,2],[3,4]]。下面我编写了一个函数,提示用户输入方阵的尺寸,然后提示用户输入for循环中的值。我有一个tempArray变量,它临时存储一行值,然后在附加到矩阵数组后被删除。出于某种原因,当我在最后打印矩阵时,得到的结果是:[[],[]。出什么事了 def proj11_1_a(): n = eval(input("Enter the size of the square matrix: ")) 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)
del tempArray[:]
else:
tempArray.append(val)
print(matrix)
proj11_1_a()
您只需删除数组元素
del 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)
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
另一个解决方案是更改以下行:
matrix.append(tempArray)
致:
此代码中没有打印对不起,我删除了该行为什么要删除阵列
del tempArray[:]
只有在数组有一行值后才会删除该数组。删除它的原因是,它可以存储下一行值,然后将其附加到矩阵数组中。这是次优的,因为您需要。。。复制对象(因此,如果对象很大,则需要线性时间)。由于最初的目的是提示用户输入,与用户输入的速度相比,开销是最小的。当然,但这并不意味着应该在其他地方编写不足的代码。我们也不应该建议学习python的人使用它(比如OP),因为无论如何,您都要使用append(val),所以最好从if/else中获取它blocks@Jjpx-这是操作代码,唯一导致问题的片段被更改,这里有很多东西可以改进@Jjpx建议,您也可以提供最佳版本。我认为两个版本都有利于OP。
matrix.append(tempArray.copy())