无法解决错误:列表索引超出范围

时间:2014-01-24 18:01:05

标签: python

我正在尝试在PHP中运行相同的代码,但它工作正常,当尝试在Python上运行它时,它给我以下错误:

if my_queue[int_neighbour]['visited'] == '0':
    IndexError: list index out of range

输入:

1 0 A 2,3
2 0 B 1,4,5
3 0 C 1,2
4 0 D 2,5
5 0 E 2,4

完整代码:

import string
import time
start_time = time.time() #starting time
file_name = input('Enter a file name: ')
f = open(file_name, 'r')
data = f.readlines()
final_data = []

for line in data:
      values = line.split()
      neighbors = values[3].split(',')
      vertex_mod = int(values[0])-1
      read_line = dict({
                'vertex': vertex_mod,
                'visited': values[1],
                'letter': values[2],
                'neighbors': neighbors
                })
      final_data.append(read_line)


def dfs(vertex, my_queue):
    if vertex['visited'] == '0':
            print(vertex['letter'])
            int_vertex = int(vertex['vertex'])
            my_queue[int_vertex]['visited'] = '1';
            for neighbour in vertex['neighbors']:
                      int_neighbour = int(neighbour)
                      if my_queue[int_neighbour]['visited'] == '0':
                          result_queue = dfs(my_queue[int_neighbour], my_queue)


      return my_queue


dfs(final_data[1], final_data)

我得到的输出似乎是正确的,但我也得到了错误。

1 个答案:

答案 0 :(得分:1)

不知道我是否真的了解您的代码,但尝试更改此行

int_neighbour = int(neighbour)

进入

int_neighbour = int(neighbour) -1

您的数据结构是:

{'neighbors': ['2', '3'], 'visited': '0', 'vertex': 0, 'letter': 'A'}
{'neighbors': ['1', '4', '5'], 'visited': '0', 'vertex': 1, 'letter': 'B'}
{'neighbors': ['1', '2'], 'visited': '0', 'vertex': 2, 'letter': 'C'}
{'neighbors': ['2', '5'], 'visited': '0', 'vertex': 3, 'letter': 'D'}
{'neighbors': ['2', '4'], 'visited': '0', 'vertex': 4, 'letter': 'E'}

看起来您使用int_neighbour作为数组的索引。该数组为零索引,输入文件使用1-5作为标识符。