2014-12-02 61 views
0

我正在用Python 3.4編寫一些簡單的遊戲。我在Python中是全新的。下面的代碼:在Python中「鑄造」爲int 3.4

def shapeAt(self, x, y): 
    return self.board[(y * Board.BoardWidth) + x] 

拋出一個錯誤:

TypeError: list indices must be integers, not float 

現在我發現,當Python的「認爲」該名單的說法是不是整數,這可能發生。你有什麼想法如何解決這個問題?

+0

x和y的類型是什麼?如果它們是字符串使用int(x)和int(y) – Hackaholic 2014-12-02 07:38:01

+1

'(y * Board.BoardWidth)+ x'打印並檢查它的值是否爲整數或浮點數。 – 2014-12-02 07:39:10

+0

@TrzyGracje你想保存x,y爲int ??? – Hackaholic 2014-12-02 07:49:32

回答

4

int((y * Board.BoardWidth) + x)使用int得到最接近零的整數。

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

,並獲得本底值使用math.floor(由m.wasowski的幫助)

math.floor((y * Board.BoardWidth) + x) 
+0

@Trzy Gracje檢查解決方案。 – 2014-12-02 07:49:05

+0

'int(x)'不返回樓層值。它向零返回最接近的整數。所以'int(-2.3)'返回'-2',而'math.floor(-2.3)'返回'-3.0'。 – 2014-12-02 08:23:35

+0

@ m.wasowski ohhh對不起,我忘了它。 – 2014-12-02 08:28:27

2

這可能是因爲您的索引是float,這些應該是ints(因爲您將它們用作數組索引)。我不會使用int(x),我想你可能打算通過一個int(如果沒有,當然使用return self.board[(int(y) * Board.BoardWidth) + int(x)])。

您可能還需要獲得本底值,讓您的指數,這裏是如何做到這一點:

import math 

def shapeAt(self, x, y): 
    return self.board[math.floor((y * Board.BoardWidth) + x)] 

您也可以使用Python的type()功能,以確定您的變量的類型。

1

如果xy是數字或代表你可以使用int投以整數文字字符串,而浮點值得到地板:

>>> x = 1.5 
>>> type(x) 
<type 'float'> 
>>> int(x) 
1 
>>> type(int(x)) 
<type 'int'> 
1

什麼是你需要檢查的x和y類型, ñ將它們轉換使用int爲整型:

def shapeAt(self, x, y): 
    return self.board[(int(y) * Board.BoardWidth) + int(x)] 

如果你想先儲存它們:

def shapeAt(self, x, y): 
    x,y = int(x),int(y) 
    return self.board[(y * Board.BoardWidth) + x] 
+0

感謝downvote和plz指定原因 – Hackaholic 2014-12-02 07:45:23

+0

REACHUS已經給出了答案? – 2014-12-02 07:45:51

+0

@VishnuUpadhyay檢查OP – Hackaholic 2014-12-02 07:46:11

0

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