[英]Python: List Index out of Range Reading from File
我正在使用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
如您所见,我分配给的索引似乎存在,但是仍然出现此错误。
您交换了高度和宽度; 外部列表的长度为height
,而不是内部的。 self.tileMap[0]
是长度为2的列表,因此可以在其上使用的最大索引为1
,而不是2
。
交换x
和y
将解决此问题:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.