我已经阅读了一个数字矩阵,我正在尝试使用每个单元格并对每个单元格进行测试。如果数字是 != 0 我想使用它,所以如果它是 0 我目前正在递增 x 和 y 以找到一个非零数。
最后,我将首先查看顶行,然后如果它们都为 0,则开始向下查看第一列,只要我仅指一个(行或列),它就可以正常工作。
为什么我会收到此错误?我是否错误地考虑了单元格的设置方式还是我的代码错误?
矩阵如下所示:
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,0,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
当我开始尝试这样做时:
y = y + 5
x = x + 5
node = Alist[x][y]
我收到一条错误消息:
node = Alist[x][y]
IndexError: list index out of range
如果我只是写:
y = y + 5
node = Alist[x][y]
print node
它完全可以正常工作,但是当我同时引入 x 和 y 时,我开始出现列表索引超出范围的问题。在我看来,它现在应该是:
node = Alist[5][5]
如果遵循矩阵,则为 0
def create_matrix(file):
with open('network.txt') as f:
Alist = []
for line in f:
part = []
for x in line.split(','):
part.append(int(x))
Alist.append(part)
return Alist
#used to set the start node, used once
def start_node(Alist):
x=0
y=0
#point node to pos [0][0] of Alist
node = Alist[x][y]
#test if node == 0
while node == 0:
y = y + 5
x = x + 5
node = Alist[x][y]
#create a list to hold co-ordinates
if node != 0:
#return node for processing by check_neighbours
return node, x, y
#def current_node(Alist, x, y)
#test neighbours to see if they can be used
def check_neighbours(node, Alist, i, j):
#print out values of x and y
print "x = %d" %i
print "y = %d" % j
print "node in check_neighbours is " + str(node)
#running of code begins here
def main():
file = ("F:/media/KINGSTON/Networking/network.txt")
Alist = create_matrix(file)
node, x, y = start_node(Alist)
check_neighbours(node, Alist, x, y)
main()