本学期我参加了Python课程,我的导师喜欢使用矩阵。
我分配的任务如下:
创建一个3行,5列的矩阵(x)。
使用从外部文件加载的给定值填充矩阵,逐行加载数字(意味着,如果您将数字替换为它们加载到矩阵中的顺序:
1,2,3
4,5,6
7,8,9 ....等。)
打印矩阵 - 将其显示在屏幕上,并将结果发送到外部文件。
给定的数字范围是1,3,5,7,9,0,2,4,6,8,0,1,2,3,4。我将这些数字存储在名为lab5matrix.dat的文件中。数字格式完全相同,逗号和所有。
" A"作为LOADX的一部分出现代表" x"。我的教授改变了这些变量,说一个人不想要过多的糖"。我不知道这意味着什么。
当我尝试运行模块时,我得到了这个:
Traceback (most recent call last):
File "E:/PythonScripts/Lab5-Matrices/lab5matrix.py", line 51, in <module>
main()
File "E:/PythonScripts/Lab5-Matrices/lab5matrix.py", line 15, in main
LOADX(infile, x)
File "E:/PythonScripts/Lab5-Matrices/lab5matrix.py", line 33, in LOADX
A[j][k] = int(templist[n])
IndexError: list index out of range
真心感谢任何帮助。
这是我的代码,缩进似乎是准确的:
def main():
#matrix initialization
x=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
#file declaration
infile = open('lab5matrix.dat','r')
outfile = open('lab5test.out', 'w')
#call functions
LOADX(infile, x)
#close files
infile.close()
infile.close()
outfile.close()
dummy = input('Press any key to continue.')
#load matrix x
def LOADX(infile, A):
#local variables
n=0
k=0
s=0
templist = (infile.readline().strip('\n').split(','))
while (k<=3):
j=0
while(j<=5):
A[j][k] = int(templist[n])
s=s+A[j][k]
j=j+1
n=n+1
k=k+1
def OUTDATA(outfile, A):
i=0
j=0
k=0
while (k<3):
print(A[k][0],A[k][1],A[k][2],A[k][3],A[k][4])
file.write[str(A[k][0])+str(A[k][1])+str(A[k][2])+str(A[k][3])+str(A[k][3])+str(A[k][4])]
k=k+1
main()
答案 0 :(得分:0)
A
是一个包含5个元素的列表。因此,您只能使用数字0到4在函数中对其进行索引。注意内部while
循环的条件。您正在使用从0到5的j
值。当j
等于5时,您将遇到问题。
外部while
循环存在类似的问题。
将来你应该尝试调试像这样的小错误。最简单的方法是使用print
语句!错误消息告诉您错误在line 33
。它还告诉您列表索引超出范围。因此,如果您只是在错误发生之前放置print(j,k,n)
,那么您可以确定自己到底出了什么问题:)
希望这会有所帮助:)
答案 1 :(得分:0)
首先,对不起,如果我不像我一样精通这个论坛的礼节。我对这种特殊的语言非常陌生 - 我对网络编程更加精通 - 虽然逻辑和概念可能有点类似于JavaScript,但发现和修复错误实际上并非如此。不管怎样,不适合我。
其次,我发布的一个小问题是一个更大的程序的一部分,该程序被指定为实验室......弄清楚我在X矩阵中做错了什么是Rosetta Stone帮助整个混乱到位。我老实说刚刚陷入困境,我不知道该怎么做。我在夏季学期学习这门课程,这是一个学期常规学期的一半,没有更少的任务或要求 - 通过这种材料快速移动不利于知识保留。
一位同学帮助我顺利完成......是的,上面发布的循环中的值存在问题。我通过将'小于或等于'更改为“小于”来修复此问题,使用所有值,但不包括运算符后面的值。
这是最终(工作)X矩阵循环:
def loadx(file,A):
#local variable
k=0
n=0
templist=file.readline().strip("\n").split(",")
while(k<5):
j=0
while(j<3):
A[k][j]=int(templist[n])
j=j+1
n=n+1
k=k+1
而且,如果有人感兴趣,我会发布程序的整个工作版本 - 基本上,我们给了两组数据,并使用这些,我们编写了一个程序来加载矩阵x(5行乘3列)从文件,加载行中的值,从文件加载矩阵y(3行,7列),加载列中的值,将x矩阵的第一列的总和加到y矩阵的第一行的总和,找到y矩阵的第0行中的最小值,并将矩阵x乘以矩阵y以生成矩阵z,并在屏幕上打印矩阵并将所有结果写入outfile。 简单吧? ; )
sumx=0
sumy=0
def main():
#Matrices declaration
x=([0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0])
y=([0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0])
z=([0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0])
#file declaration
infilex=open("lab5x.dat","r")
infiley=open("lab5y.dat","r")
outfile=open("lab5.out","w")
#variable declaration
totSum=0
small=0
#call functions
loadx(infilex,x)
loady(infiley,y)
computez(x,y,z)
summation(x,y)
small=float(smallest(y))
totSum=(sumx+sumy)
outdata(outfile,x,y,z,small,totSum)
#close files
infilex.close()
infiley.close()
outfile.close()
dummy=input("Please press any key to continue")
#Functions
def loadx(file,A):
#local variable
k=0
n=0
templist=file.readline().strip("\n").split(",")
while(k<5):
j=0
while(j<3):
A[k][j]=int(templist[n])
j=j+1
n=n+1
k=k+1
def loady(file,B):
#local variable
k=0
n=0
templist=file.readline().strip("\n").split(",")
while(k<7):
j=0
while(j<3):
B[j][k]=int(templist[n])
j=j+1
n=n+1
k=k+1
def computez(A,B,C):
i=0
while(i<5):
j=0
while(j<7):
k=0
while(k<3):
C[i][j]=C[i][j]+A[i][k]*B[k][j]
k=k+1
j=j+1
i=i+1
def summation(A,B):
j=0
k=0
totSum=0
#global variable
global sumx
global sumy
while(k<5):
sumx=A[k][1]+sumx
k=k+1
while(j<7):
sumy=B[1][j]+sumy
j=j+1
def smallest(B):
k=0
small=0
while(k<7):
if small>B[0][k]:
small=B[0][k]
k=k+1
return(small)
def outdata(file,A,B,C,D,E):
#local variable
kA=0
kB=0
kC=0
global sumx
global sumy
print("OUTPUT", ("\n"))
print("------")
print("X Matrix", ("\n"))
file.write(str("OUTPUT")+"\n")
file.write("X Matrix"+"\n")
while (kA<5):
print("\n")
j=0
while(j<3):
print(A[kA][j])
file.write(str(A[kA][j])+" ")
j=j+1
kA=kA+1
file.write("\n")
file.write("\n")
print("\n")
print("Y Matrix", ("\n"))
file.write("Y Matrix"+"\n")
while(kB<3):
print("\n")
j=0
while(j<7):
print(B[kB][j]," ")
file.write(str(B[kB][j])+" ")
j=j+1
kB=kB+1
file.write("\n")
file.write("\n")
print("\n")
print("Z Matrix", ("\n"))
file.write("Z Matrix"+"\n")
while (kC<5):
j=0
while(j<7):
print(C[kC][j]," ")
file.write(str(C[kC][j])+" ")
j=j+1
kC=kC+1
print("\n")
file.write("\n")
file.write("Sumx: "+str(sumx)+"\n")
file.write("Sumy: "+str(sumy)+"\n")
file.write("Smallest: "+str(D)+"\n")
file.write("Total Sum: "+str(E))
main()
答案 2 :(得分:0)
只是为了好玩: - )
请参阅下文,了解矩阵问题的更多Pythonic实现。我只实现了矩阵乘法,因为这是最难的:
#!/usr/bin/python
# number of rows and colums for matrix x
NROWSX=5
NCOLSX=3
# number of rows and colums for matrix y
NROWSY=3
NCOLSY=7
# class to hold matrix of any dimension
# and some matrix operations
class Matrix(object):
def __init__(self, nrows, ncols):
# define matrix (set dimensions)
self.nrows = nrows
self.ncols = ncols
# create matrix: pass a list and convert it to rows
def fill(self, values):
self.matrix = list(self.chunks(values, self.ncols))
# transpose the matrix
def transpose(self):
# serialise matrix data
__serial = []
for row in self.matrix:
__serial += row
# create new (empty) matrix
__transp = map(list, [[]] * self.ncols)
# populate matrix
for i in xrange(self.nrows):
for j in xrange(self.ncols):
__transp[j].append(__serial[i * self.ncols + j])
# done
__new = Matrix(self.ncols, self.nrows)
__new.matrix = __transp
return __new
# helper function to cut up a list in equally sized chunks
def chunks(self, l, n):
"""Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i+n]
def __mul__(self, other):
# our ncols must equal other's nrows for multiplication to work
if (self.ncols == other.nrows):
# multiply works best on transposed matrix
other = other.transpose()
# execute multiplication serially
__serial = []
for r1 in self.matrix:
for r2 in other.matrix:
# calculate sum over row x column
s = 0
for i in (x*y for x,y in zip(r1,r2)):
s += i
__serial.append(s)
# turn data into new matrix
__new = Matrix(self.nrows, other.nrows)
__new.fill(__serial)
return __new
else:
raise ValueError, "columns and rows don't match"
def __rmul__(self, other):
# haven't done this one yet...
print '__rmul__ not available'
return None
if __name__ == "__main__":
datax = [1,3,5,7,9,0,2,4,6,8,0,1,2,3,4] # 5x3
datay = [6,8,4,0,7,1,2,2,3,7,1,0,1,8,9,6,4,5,7,9,8] # 3x7
# create and populate matrix x
mtx_x = Matrix(NROWSX, NCOLSX)
mtx_x.fill(datax)
# create and populate matrix y
mtx_y = Matrix(NROWSY, NCOLSY)
mtx_y.fill(datay)
print "\nmatrix x:"
print mtx_x.matrix
print "\nmatrix y:"
print mtx_y.matrix
# multiply both matrices
mtx_z = mtx_x * mtx_y
print "\nmatrix z:"
print mtx_z.matrix