索引错误:列表索引超出范围(Python)--打印到控制台
我遇到了以下错误,即:索引错误:列表索引超出范围(Python)--打印到控制台,python,list,printing,console,Python,List,Printing,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.wri
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
所需的结果是控制台显示:
======================
= =
= Pls Work. =
= =
======================
我将其用作创建上述代码的指南
提前谢谢 在createBoard()方法中:
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
def write( self, word ):
self.l[ self.y ] [ self.x : ( self.x + len( word ) ) ] = word
您正在创建一个长度和高度正确的列表,但从未将其分配给self.l
。因此,self.l
仍然是长度为0的列表
另外,在write()
方法中:
def createBoard( self ):
listBig = [ ['`'] * self.screenWidth for _ in range( self.screenHeight ) ]
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
,这会有所帮助。我建议将.init\uuu()
、.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()
我发誓这是今天的最后一个问题:)我没有注意到所有这些bug。。感谢您的帮助,并展示了制作我的程序的更好方法!