2014-06-30 70 views
0

我正在使用python 2.5(我知道這是一箇舊版本),並且我不斷收到一個令人沮喪的'List index out of range'異常。我工作的基於區塊的遊戲,波紋管是創建地圖,我遇到問題的代碼:Python:列表索引超出範圍從文件中讀取

#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 

正如你所看到的,我分配給指數似乎存在,但我仍然得到這個錯誤。

+0

這不是拋出異常的讀數。 –

+0

我知道,我必須把它放在標題中,因爲有人已經有了我將要使用的標題。什麼是例外是它說索引超出範圍。 – user3050810

回答

1

您調換了高度和寬度; 外部列表的長度爲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)) 
+0

交換高度和長度並不能解決問題,但我仍然遇到錯誤。 – user3050810

+0

@ user3050810:請注意,'x'現在是循環範圍(self.height)',而不是**'self.length'。 –

+0

謝謝,一旦我看了你的答案,我就在紙上找出了問題,並意識到了我的錯誤。 – user3050810