【问题标题】:"Cast" to int in Python 3.4在 Python 3.4 中“强制转换”为 int
【发布时间】:2014-12-02 07:36:42
【问题描述】:

我正在用 Python 3.4 编写一些简单的游戏。我对 Python 完全陌生。代码如下:

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

抛出错误:

TypeError: list indices must be integers, not float

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

【问题讨论】:

  • x 和 y 的类型是什么???,如果是字符串使用 int(x) 和 int(y)
  • (y * Board.BoardWidth) + x 打印并检查值是整数还是浮点数。
  • @TrzyGracje 你想将 x,y 保存为 int???
  • 你能说明你是如何使用这个函数的吗?Board.BoardWidth来自哪里?

标签: python python-3.x


【解决方案1】:

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)

【讨论】:

  • @Trzy Gracje 检查解决方案。
  • int(x) 不返回底值。它返回最接近零的整数。所以int(-2.3) 返回-2,而math.floor(-2.3) 返回-3.0
  • @m.wasowski 哦,对不起,我忘了。
【解决方案2】:

如果xy 是表示数字文字的数字或字符串,您可以使用int 强制转换为整数,而浮点值会被取底:

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

【讨论】:

    【解决方案3】:

    这可能是因为您的索引是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() 函数来识别变量的类型。

    【讨论】:

      【解决方案4】:

      你需要检查 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]
      

      【讨论】:

      • @VishnuUpadhyay 检查 OP 的评论
      • 在这种情况下,您不会在 Python 中检查类型。您只需尝试转换它,并在发生时捕获异常。
      • 我告诉 OP 检查它获取的数据类型,是浮点数还是字符串,还是列表。这样会更清楚,TypeError可以处理
      • 不管怎样,你仍然可能得到一个TypeError,你不知道Board.BoardWidth是什么类型。如果它是 float,您会得到 float 作为括号中表达式的结果。
      【解决方案5】:

      基本上,您只需调用 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 
      

      如果您是初学者,您可能会感到惊讶,但在 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! ;)

      【讨论】:

        猜你喜欢
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多