1

在我的函数中,我检查输入的类型以使其有效(例如 - 对于检查“n”素数的函数,我不希望将“n”作为字符串输入)。检查longs 和ints 时会出现问题。在 Python 3.3 中,他们删除了long-type 编号,因此出现了问题:

def isPrime(n):
    """Checks if 'n' is prime"""
    if not isinstance(n, int): raise TypeError('n must be int')
    # rest of code

这适用于 v2.7 和 v3.3。但是,如果我在 Python 2.7 程序中导入此函数,并long为 'n' 输入一个 -type 数字,如下所示:isPrime(123456789000),它显然会引发 aTypeError因为 'n' 的类型是long,而不是int

long那么,我如何检查它对于s 和s 的v2.7 和 v3.3 是否都是有效输入int

谢谢!

4

3 回答 3

7

我能想到的一个方法是:

from numbers import Integral

>>> blah = [1, 1.2, 1L]
>>> [i for i in blah if isinstance(i, Integral)]
[1, 1L]

编辑(在@martineau 的富有洞察力的评论之后)

蟒蛇 2.7:

>>> map(type, [1, 1.2, 2**128])
[<type 'int'>, <type 'float'>, <type 'long'>]

蟒蛇 3.3:

>>> list(map(type, [1, 1.2, 2**128]))
[<class 'int'>, <class 'float'>, <class 'int'>]

该示例仍然使用isinstance(n, numbers.Integral)但更加连贯。

于 2013-02-11T18:06:53.410 回答
0
def isPrime(n):
    """Checks if 'n' is prime"""
    try:
        n = int(n)
    except:
        raise TypeError('n must be int')
    # rest of code
于 2013-02-11T20:05:59.893 回答
-2

来自:http ://docs.python.org/3.1/whatsnew/3.0.html#integers

sys.maxint 常量已被删除,因为整数值不再有限制。但是,sys.maxsize 可以用作大于任何实际列表或字符串索引的整数。它符合实现的“自然”整数大小,并且通常与同一平台上先前版本中的 sys.maxint 相同(假设相同的构建选项)。

if not isinstance(n, int) or n > sys.maxsize: raise TypeError('n must be int')

可能适用于区分 int 和 long。

于 2013-02-11T19:36:25.703 回答