基本上,你只需要調用一個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