繁体   English   中英

用Python制作矩阵

[英]Making a Matrix in Python

我写了代码,它给出了这个错误:

列表索引超出范围

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

更正的代码:

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

您将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

即使事先不知道尺寸,也可以使用这种方法。

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)

就像其他人所说的那样,您的代码存在的问题是您没有为矩阵的行创建列表。 但是,请注意,将矩阵实现为列表列表的效率非常低,除了作为学习练习之外。 numpy模块很好地实现了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM