Python 3.3.3:类型错误:列表索引必须是整数,而不是浮点数 [英] Python 3.3.3: TypeError: list indices must be integers, not float
问题描述
我有一个 python 2.7.6 程序,我想转换为 3.3.3.
I have a python 2.7.6 program I want to convert to 3.3.3.
我收到一个错误:
File "H:\My Game Python 3,3\MoonSurvival.py", line 199, in run
self.moon.levelStructure[x][y] = None
回溯是:
Traceback (most recent call last):
File "H:\My Game Python 3,3\MoonSurvival.py", line 591, in <module>
Game().run()
File "H:\My Game Python 3,3\MoonSurvival.py", line 199, in run
self.moon.levelStructure[x][y] = None
TypeError: list indices must be integers, not float
但是当我查看 levelStructure
的代码时,没有任何问题.这是分配 levelStructure 的代码:
But when I look at the code for the levelStructure
there is nothing wrong. This is the code that assigns levelStructure:
tempBlock = Block(x*64, y*64)
# add block to both and self.levelStructure
self.levelStructure[x][y] = tempBlock
如您所见,levelStructure
是 tempBlock.随着它的乘法,它似乎给出了一个浮动.我知道除法是两个斜线 /
.我试图乘以 '*' 但我仍然得到错误.我不完全熟悉 3.3.3 语法,因为我通常使用 2.7.6.
As you can see the levelStructure
is tempBlock. As it is multiplying, it seems to be giving a float. I know with division it is two slashes /
. I have tried to multiply '*' but I still get the error. I am not entirely familiar with 3.3.3 syntax as I generally use 2.7.6.
块代码:
class Block(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('data/images/moon.jpg')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def render(self, surface):
surface.blit(self.image, self.rect)
导致此错误的原因是什么?
What causes this error?
推荐答案
由于您正在从 Python 2.7 -> Python 3.x 转换,这几乎肯定是楼层划分的问题.
Since you're converting from Python 2.7 -> Python 3.x, it's almost CERTAINLY an issue with floor division.
我不确定您在何处生成 x
和 y
,但是如果您在任何时候将这些数字除以任何值,请确保使用//
Python 3 中的运算符,如果您希望得到一个整数结果.
I'm not sure where exactly you're generating your x
and y
, but if at any point you divide those numbers by anything, make sure you use the //
operator in Python 3 if you expect an integer result.
在 Python 2 中,5/2 == 2
并且您必须执行 5/2.0
才能获得浮点结果.在 Python 3 中,5/2 == 2.5
并且您必须执行 5//2
才能获得除法的地板整数结果.很有可能当你在你的 x
和 y
上操作时,你将它除以在 Python 2 中给你一个整数但在 Python 3 中给你的东西那个浮点数,所以当你尝试将它用作列表索引时...BOOM
In Python 2, 5/2 == 2
and you had to do 5/2.0
to get the floating point result. In Python 3, 5/2 == 2.5
and you have to do 5//2
to get the floored integer result of the division. Chances are whenever you're operating on your x
and y
, you're dividing it by something that in Python 2 gave you an integer but in Python 3 is leaving you with that floating point, so when you try to use it as a list index...BOOM
这篇关于Python 3.3.3:类型错误:列表索引必须是整数,而不是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!