基本上,你只需要调用一个int()
内置:
def shapeAt(self, x, y):
return self.board[int((y * Board.BoardWidth) + x))
但是,如果你想用它来做任何事情,而不是练习或肮脏的脚本,你应该考虑处理边缘情况。如果你在某个地方犯了错误,并把奇怪的价值观作为论据呢?
更强大的解决方案是:
def shapeAt(self, x, y):
try:
calculated = int((y * Board.BoardWidth) + x)
# optionally, you may check if index is non-negative
if calculated < 0:
raise ValueError('Non-negative index expected, got ' +
repr(calculated))
return self.board[calculated]
# you may expect exception when converting to int
# or when index is out of bounds of your sequence
except (ValueError, IndexError) as err:
print('error in shapeAt:', err)
# handle special case here
# ...
# None will be returned here anyway, if you won't return anything
# this is just for readability:
return None
如果你是初学者,你可能会suprising,但在Python负索引是完全有效的,但他们有特殊的含义。你应该阅读它,并决定是否允许它们在你的函数中(在我的例子中,它们是不允许的)。
您可能还需要阅读有关规则转换为int的:
https://docs.python.org/2/library/functions.html#int
和考虑,如果对你来说会不会是更好的用户地板或天花板,您尝试强制转换为int之前:
https://docs.python.org/2/library/math.html#math.floor
https://docs.python.org/2/library/math.html#math.ceil
只要确保,你哈在打电话给那些人之前,我有一个float
! ;)
x和y的类型是什么?如果它们是字符串使用int(x)和int(y) – Hackaholic 2014-12-02 07:38:01
'(y * Board.BoardWidth)+ x'打印并检查它的值是否为整数或浮点数。 – 2014-12-02 07:39:10
@TrzyGracje你想保存x,y为int ??? – Hackaholic 2014-12-02 07:49:32