简体   繁体   English

索引超出范围,Python?

[英]Index out of range , Python?

My program is supposed to auto-fill (like ms paint) a text file. 我的程序应该自动填充(如ms paint)一个文本文件。 I cannot figure out why this is giving me an index out of range. 我不知道为什么这会给我超出范围的索引。

Also my fill function must be recursive, and making the call to neighboring cells in the following order: above,right,below, and left. 同样,我的fill函数必须是递归的,并按以下顺序调用相邻的单元格:上,右,下和左。 Better or more efficient ways to do this please let me know(that's if i'm even doing what I want it to be doing). 更好或更有效的方式来做到这一点,请让我知道(如果我什至在做我想做的事情)。

[int(row)][int(col)] doesn't work as you expect. [int(row)][int(col)]无法正常工作。

It creates a list with one element, which is int(row) and then tries to access its int(col) element. 它创建一个包含一个元素的列表,该元素为int(row) ,然后尝试访问其int(col)元素。 Actually this line will raise an exception every time int(col) is > 0 . 实际上,每当int(col) > 0时,此行都会引发异常。

Instead, you should use a tuple: 相反,您应该使用元组:

p = int(row), int(col)

but keep in mind that it is immutable, so you can't change it directly later: 但请记住,它是不可变的,因此以后不能直接更改它:

p = int(row), int(col)
p[0] = 3
>> TypeError: 'tuple' object does not support item assignment

Though you can reassign a new tuple: 尽管您可以重新分配一个新的元组:

p = int(row), int(col)
p = 3, int(col)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM