我正在使用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
正如你所看到的,我分配給指數似乎存在,但我仍然得到這個錯誤。
這不是拋出異常的讀數。 –
我知道,我必須把它放在標題中,因爲有人已經有了我將要使用的標題。什麼是例外是它說索引超出範圍。 – user3050810