嘿我写一个函数,它接受一个矩阵输入,例如下面的一个,并返回它的逆,其中所有的1秒被改变为0和所有的0改变为1秒,同时保持从左上角到右下角0s的对角线。蟒矩阵 - 列表索引超出范围
一个例子输入:
g1 = [[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]]
函数应输出此:
g1 = [[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 0]]
当运行程序时,它引发一个“列表索引超出范围“错误。我敢肯定,这是因为我已经设置了循环试图访问不存在的价值,但如何让未知的行和列大小的输入?我只知道如何使用单个列表来完成此操作,但列表的列表是?下面是函数,不包括测试功能调用它:
def inverse_graph(graph):
# take in graph
# change all zeros to ones and ones to zeros
r, c = 0, 0 # row, column equal zero
while (graph[r][c] == 0 or graph[r][c] == 1): # while the current row has a value.
while (graph[r][c] == 0 or graph[r][c] == 1): # while the current column has a value
if (graph[r][c] == 0):
graph[r][c] = 1
elif (graph[r][c] == 1):
graph[r][c] = 0
c+=1
c=0
r+=1
c=0
r=0
# sets diagonal to zeros
while (g1[r][c] == 0 or g1[r][c] == 1):
g1[r][c]=0
c+=1
r+=1
return graph
我想,如果你花一些时间来学习[list comprehensions](http://www.python.org/dev/peps/pep-0202/),那么你的代码的可读性,正确性和速度会大大提高。 ) – erikbwork
如果你使用了很多矩阵/二维数组,NumPy非常有用。 – ninMonkey