簡體   English   中英

Python:超出文件讀取范圍的列表索引

[英]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

交換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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM