列表索引超出范围?它不应该

时间:2013-03-30 21:53:44

标签: list python-3.x

def trav(r,c):
  #print("(",r,",",c,")")
  ch = a[r+1][c+1]

  lu= a[r][c]
  #print(lu)
  u = a[r][c+1]
  #print(u)
  ru= a[r][c+2]
  #print(ru)

  l = a[r+1][c]
  #print(l)
  r = a[r+1][c+2]
  #print(r)

  ld= a[r+2][c]
  #print(ld)
  d = a[r+2][c+1]
  #print(d)
  rd= a[r+2][c+2]
  #print(rd)

  a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = 0

  if(ch == lu-1):
    a1 = trav(r-1,c-1)

  if(ch == u-1):
    a2 = trav(r-1,c)

  if(ch == ru-1):
    a3 = trav(r-1,c+1)

  if(ch == l-1):
    a4 = trav(r,c-1)

  if(ch == r-1):
    a5 = trav(r,c+1)

  if(ch == ld-1):
    a6 = trav(r+1,c-1)

  if(ch == d-1):
    a7 = trav(r+1,c)

  if(ch == rd-1):
    a8 = trav(r+1,c+1)

  return max(a1,a2,a3,a4,a5,a6,a7,a8) + 1


while(1):
  row,col = [int(x) for x in input().split(" ")]

  if(row == 0):
    break

  a = []
  for index in range(10):
    a.append([])
    for jindex in range(10):
      a[index].append('a')

  b = []
  for index in range(row):
    str = input()
    for jindex in range(col):
      a[index+1][jindex + 1] = ord(str[jindex])
      if(str[jindex] == 'A'):
        b.append([index,jindex])

  #print (a)
  #print (b)

  ans = max([trav(x[0],x[1]) for x in b])

  print(ans)

代码生成以下错误

 Traceback (most recent call last):   File "C:/Users/DELL/Desktop/ABCPATH.py", line 80, in <module>
    ans = max([trav(x[0],x[1]) for x in b])   File "C:/Users/DELL/Desktop/ABCPATH.py", line 80, in <listcomp>
    ans = max([trav(x[0],x[1]) for x in b])   File "C:/Users/DELL/Desktop/ABCPATH.py", line 17, in trav
    ld= a[r+2][c] IndexError: list index out of range

但根据我不应该,因为我是python的新手,我无法调试它。请帮忙

采取的样本输入:

4 3
ABC
CFG
BDH
ABC

1 个答案:

答案 0 :(得分:1)

打破

r = a [r + 1] [c + 2]

你要重新分配该行中'r'的值。另请注意,您不应将字符串命名为“str”,因为它是python字符串模块的名称,您将无法使用它。