2014-12-02 63 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! ;)