在Python 3.4中"转换"为int

Trz*_*cje 8 python python-3.x

我在Python 3.4中编写了一些简单的游戏.我是Python的新手.代码如下:

def shapeAt(self, x, y):
    return self.board[(y * Board.BoardWidth) + x]
Run Code Online (Sandbox Code Playgroud)

抛出错误:

TypeError: list indices must be integers, not float
Run Code Online (Sandbox Code Playgroud)

现在我发现当Python"认为"列表参数不是整数时,可能会发生这种情况.你知道如何解决这个问题吗?

Vis*_*yay 14

int((y * Board.BoardWidth) + x)用于int将最接近的整数逼近零.

def shapeAt(self, x, y):
    return self.board[int((y * Board.BoardWidth) + x)] # will give you floor value.
Run Code Online (Sandbox Code Playgroud)

和使用楼层价值math.floor(在m.wasowski的帮助下)

math.floor((y * Board.BoardWidth) + x)
Run Code Online (Sandbox Code Playgroud)

  • `int(x)`不返回底值。它将最接近的整数返回零。所以`int(-2.3)`返回`-2`,而`math.floor(-2.3)`返回`-3.0`。 (2认同)

fam*_*kin 5

如果xy是数字或表示数字文字的字符串,则可用于int强制转换为整数,而浮点值则为下限:

>>> x = 1.5
>>> type(x)
<type 'float'>
>>> int(x)
1
>>> type(int(x))
<type 'int'>
Run Code Online (Sandbox Code Playgroud)