[英]Index Error: list index out of range (Python) — Printing to Console
我無法跟蹤我得到的錯誤:
Traceback (most recent call last):
File "/Users/joelwilliams/Desktop/delete me", line 30, in <module>
v.writef( '======================', 10, 10 )
File "/Users/joelwilliams/Desktop/delete me", line 24, in writef
self.write( word )
File "/Users/joelwilliams/Desktop/delete me", line 15, in write
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
IndexError: list index out of range
主要代碼在這里:
class board():
def __init__( self ):
self.x, self.y = 0, 0
self.l = []
self.screenWidth, self.screenHeight = 0, 0
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
def setup( self, sw, sh ):
self.screenWidth = sw - 1
self.screenHeight = sh - 1
def write( self, word ):
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
def draw( self ):
for v in self.l:
print(''.join(v))
def writef( self, word, y, x ):
self.cursorPosX = x - 1
self.cursorPosY = y - 1
self.write( word )
v = board()
v.setup( 75, 20 )
v.createBoard()
v.writef( '======================', 10, 10 )
v.writef( '= =', 11, 10 )
v.writef( '= Pls Work. =', 12, 10 )
v.writef( '= =', 13, 10 )
v.writef( '======================', 14, 10 )
v.draw()
所需的結果是控制台顯示:
======================
= =
= Pls Work. =
= =
======================
我提前用這個作為指導來創建上面的代碼!
在您的createBoard()
方法中:
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
您正在創建正確長度和高度的列表,但您從未將其分配給self.l
所以self.l
仍然是長度為0的列表。
另外,在write()
方法中:
def write( self, word ):
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
看起來你想要self.cursorPosX
(和Y)而不是self.x
和self.y
進行這兩項更改,您的程序應該執行您要執行的操作。
你的代碼
self.l == []
) bigList
; 也許你打算設置self.l
(但仍然是self.l == []
) cursorPosX
和cursorPosY
; 我假設你打算設置x
和y
(仍然是self.l == []
) self.l
元素的元素(而self.l == []
) 如果你真的self.l
某個地方初始化self.l
會有所幫助。 我建議將.__init__()
.setup()
和.createBoard()
合並為一個,類似於.write()
和.writef()
。 像這樣的東西::
class Board():
def __init__(self, width, height):
self.l = [['`'] * (width - 1) for _ in range(height - 1)]
def write(self, text, x, y):
dx = x + len(text)
self.l[y][x:dx] = text
def draw(self):
for row in self.l:
print(''.join(row))
請注意,無用的成員變量screenWidth
, screenHeight
, x
, y
, cursorPosX
和cursorPosY
都已被刪除。
要使用此新代碼:
board = Board(75, 20)
board.write('======================', 10, 10)
board.write('= =', 11, 10)
board.write('= Pls Work. =', 12, 10)
board.write('= =', 13, 10)
board.write('======================', 14, 10)
board.draw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.