我编写了代码,它给出了这个错误:
列表索引超出范围
n = int(input("Enter the order of the matrix:"))
matrix = []
count = 0
spam = 0
while spam < n + 1:
while count < n + 1:
j = int(input("Enter the element:"))
matrix[spam][count] = j
count = count + 1
spam = spam + 1
print matrix
答案 0 :(得分:1)
更正后的代码:
n = int(input("Enter the order of the matrix:"))
#Mistake 1: You have not declared a 2D matrix
matrix = [[None for x in range(n)] for x in range(n)]
count = 0
spam = 0
#Mistake 2: spam and count should be less than n
while spam < n:
while count < n:
j = int(input("Enter the element:"))
matrix[spam][count] = j
count = count + 1
count = 0
spam = spam + 1
print matrix
答案 1 :(得分:1)
您声明matrix
是一个很好的列表,但您忘记声明matrix[spam]
也是一个列表。要将和元素添加到列表中,您必须使用append而不是简单地设置不存在的索引。
你可以简单地修复:
n=int(input("Enter the order of the matrix:"))
matrix=[]
count=0
spam=0
while spam<n+1:
matrix.append([]) # <= add an empty list
while count<n+1:
j=int(input("Enter the element:"))
matrix[spam].append(j)
count=count+1
spam=spam+1
print matrix
即使尺寸未知 a priori ,这种方式也是可用的。
答案 2 :(得分:0)
def seqmatrix(matrix):
print ' '
for i in range(len(matrix)):
print matrix[i]
print
def main():
matrix = [[random.randrange(10)]*4 for i in range(4)]
print seqmatrix(matrix)
答案 3 :(得分:0)
正如其他人所说,您的代码存在的问题是您没有为矩阵的行创建列表。但请注意,将矩阵作为列表列表实施效率非常低,除非是学习练习。 numpy
module具有出色的n维数组实现,使用起来既高效又直观。例如:
import numpy as np
n = int(input("Enter the order of the matrix:"))
matrix = np.zeros((n, n))
for spam in xrange(n):
for count in xrange(n):
num = int(input("Enter the element:"))
matrix[spam][count] = num
print matrix