在我的函数中,我检查输入的类型,以确保它是有效的(例如,对于检查'n‘素性的函数,我不希望'n’作为字符串输入)。在检查longs和ints时出现问题。在Python3.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都是通用的。但是,如果我在Python2.7程序中导入此函数,并为'n‘输入一个long-type编号,例如:isPrime(123456789000),它显然会引发一个TypeError,因为'n’属于long类型,而不是int类型。
那么,如何检查对于longs和ints的v2.7和v3.3输入是否有效?
谢谢!
发布于 2013-02-12 02:06:53
我能想到的一种方法是:
from numbers import Integral
>>> blah = [1, 1.2, 1L]
>>> [i for i in blah if isinstance(i, Integral)]
[1, 1L]编辑(在来自@martineau的富有洞察力的评论之后)
Python 2.7:
>>> map(type, [1, 1.2, 2**128])
[<type 'int'>, <type 'float'>, <type 'long'>]Python 3.3:
>>> list(map(type, [1, 1.2, 2**128]))
[<class 'int'>, <class 'float'>, <class 'int'>]该示例仍然适用于使用isinstance(n, numbers.Integral),但更加连贯。
发布于 2013-02-12 04:06:00
def isPrime(n):
"""Checks if 'n' is prime"""
try:
n = int(n)
except:
raise TypeError('n must be int')
# rest of code发布于 2013-02-12 03:36:26
来自: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。
https://stackoverflow.com/questions/14818011
复制相似问题