在 Python 3.4 中“转换”为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27244123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:34:02  来源:igfitidea点击:

"Cast" to int in Python 3.4

pythonpython-3.x

提问by Trzy Gracje

I am writing some simple game in Python 3.4. I am totally new in Python. Code below:

我正在用 Python 3.4 编写一些简单的游戏。我是 Python 的新手。代码如下:

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

Throws an error:

抛出错误:

TypeError: list indices must be integers, not float

For now I have found that this may happen when Python "thinks" that list argument is not an integer. Do you have any idea how to fix that?

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

采纳答案by Vishnu Upadhyay

int((y * Board.BoardWidth) + x)use intto get nearest integer towards zero.

int((y * Board.BoardWidth) + x)用于int获得最接近零的整数。

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

and to get floor value use math.floor(by help of m.wasowski)

并获得底价使用math.floor(在 m.wasowski 的帮助下)

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

回答by syntagma

This is probably because your indices are of type floatwhere these should be ints(because you are using them as array indices). I wouldn't use int(x), I think you probably intended to pass an int(if not, use return self.board[(int(y) * Board.BoardWidth) + int(x)]of course).

这可能是因为您的索引属于float它们应该所在的类型ints(因为您将它们用作数组索引)。我不会使用int(x),我想你可能打算通过一个int(如果没有,return self.board[(int(y) * Board.BoardWidth) + int(x)]当然使用)。

You may also want to get floor value to get your index and here is how to do it:

您可能还想获得底价来获得您的指数,这是如何做到的:

import math

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

You can also use Python's type()function to identify type of your variables.

您还可以使用 Python 的type()函数来识别变量的类型。

回答by famousgarkin

If x, yare numbers or strings representing number literals you can use intto cast to integer, while floating point values get floored:

如果x,y是代表数字文字的数字或字符串,您可以使用它int来转换为整数,而浮点值会被限制:

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

回答by Hackaholic

what is the type of x and y you need to check that, then convert them to integer type using int:

您需要检查 x 和 y 的类型是什么,然后使用int以下方法将它们转换为整数类型:

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

if you want to first store them:

如果你想先存储它们:

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

回答by m.wasowski

Basically, you just call a int()builtin:

基本上,您只需调用一个int()内置函数:

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

However, if you want to use it to anything more than practise or dirty script for you, you should think of handling edge cases. What if you made mistake somewhere and put weird values as arguments?

但是,如果您想将它用于练习或脏脚本之外的任何事情,您应该考虑处理边缘情况。如果你在某处犯了错误并将奇怪的值作为参数怎么办?

The more robust solution would be:

更强大的解决方案是:

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 

If you are beginner, you might be suprising, but in Python negative indexes are perfectly valid, but they have special meanings. You should read about it, and decide if you want to allow them in your function (in my example they are disallowed).

如果您是初学者,您可能会感到惊讶,但在 Python 中负索引是完全有效的,但它们具有特殊的含义。您应该阅读它,并决定是否要在您的函数中允许它们(在我的示例中它们是不允许的)。

You may also want to read about rules of converting to int:

您可能还想了解转换为 int 的规则:

https://docs.python.org/2/library/functions.html#int

https://docs.python.org/2/library/functions.html#int

and consider, if for you it would not be better to user floor or ceiling, before you try to cast to int:

并考虑,如果对您来说,在尝试转换为 int 之前使用 floor 或天花板不会更好:

https://docs.python.org/2/library/math.html#math.floor

https://docs.python.org/2/library/math.html#math.floor

https://docs.python.org/2/library/math.html#math.ceil

https://docs.python.org/2/library/math.html#math.ceil

Just make sure, you have a floatbefore calling those! ;)

只要确保,float在调用它们之前你有一个!;)