Python:列表索引超出范围从文件读取

时间:2014-06-30 11:36:05

标签: python list python-2.7 exception indexing

我使用的是python 2.5(我知道它是一个旧版本)而且我一直在让一个非常令人沮丧的列表索引超出范围'例外。我正在开发基于磁贴的游戏,而下面是创建地图的代码我遇到了以下问题:

#Creates the list
def setMapSize(self):
    l = raw_input('Custom Map length: ')
    h = raw_input('Custom Map height: ')
    if not(l=='')and not(h==''):
        self.length = int(l)
        self.height = int(h)
        self.tileMap = [[i]*self.length for i in xrange(self.height)]
        print self.tileMap

#Load each element of the list from a text file
def loadMap(self,filePath='template.txt'):
    loadPath = raw_input('Load the map: ')
    if loadPath =='':
        self.directory = 'c:/Python25/PYGAME/TileRpg/Maps/' + filePath
        print 'Loading map from ',self.directory
        readFile = open(self.directory,'r')

        for y in xrange(self.height):
            for x in xrange(self.length):
                #reads only 1 byte (1 char)
                print '---Location: ',x,y
                print self.tileMap
                self.tileMap[x][y]=int(readFile.read(1))

        print 'Loaded map:',self.tileMap
        readFile.close()
        print 'Map loaded\n'

以下是我收到的输出和错误消息,如果您知道发生了什么,请告诉我:

Main began

Map began initialization
Map initialized

Custom Map length: 2
Custom Map height: 5
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
Load the map: 
Loading map from  c:/Python25/PYGAME/TileRpg/Maps/template.txt
---Location:  0 0
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
---Location:  1 0
[[9, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
---Location:  0 1
[[9, 0], [9, 0], [0, 0], [0, 0], [0, 0]]
---Location:  1 1
[[9, 9], [9, 0], [0, 0], [0, 0], [0, 0]]
---Location:  0 2
[[9, 9], [9, 9], [0, 0], [0, 0], [0, 0]]
Traceback (most recent call last):
  File "C:\Python25\PYGAME\TileRpg\LevelEditorMain.py", line 7, in <module>
    class Main():
  File "C:\Python25\PYGAME\TileRpg\LevelEditorMain.py", line 17, in Main
    tileMap.loadMap()
  File "C:\Python25\PYGAME\TileRpg\Map.py", line 48, in loadMap
    self.tileMap[x][y]=int(readFile.read(1))
IndexError: list assignment index out of range

正如您所看到的,我指定的索引似乎存在,但我仍然会收到此错误。

1 个答案:

答案 0 :(得分:2)

你交换了高度和宽度; 外部列表的长度为height,而不是内部。 self.tileMap[0]是一个长度为2的列表,因此您可以使用的最大索引为1,而不是2

交换xy可解决此问题:

for x in xrange(self.height):
    for y in xrange(self.length):
        #reads only 1 byte (1 char)
        print '---Location: ',x,y
        print self.tileMap
        self.tileMap[x][y]=int(readFile.read(1))

您不需要在此处使用索引,您可以直接更改列表:

for row in self.tileMap:
    row[:] = [readFile.read(1) for _ in row]

您可以一次阅读一行:

for row in self.tileMap:
    row[:] = map(int, readFile.read(self.length))