1
roricon 2014-08-17 12:35:40 +08:00 2
https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy
你可以直接检测是否继承自numbers.Number类 from numbers import Number >>>isinstance(1, Number) >>>True >>>isinstance(1.1111, Number) >>>True |
3
hahastudio 2014-08-17 13:24:00 +08:00 1
你也许需要 float("nan") 和 math.isnan(x)
>>> float("nan") nan >>> nan = float("nan") >>> import math >>> math.isnan(nan) True >>> math.isnan(1) False >>> math.isnan(nan + 1) True |
4
ZzFoo OP @hahastudio 谢谢啊。但是math.isnan()只接受float类型做参数,又怎么用它来判断变量类型呢
|
6
ZzFoo OP @msg7086 float()可以把纯数字的字符串和‘nan’这个字符串转换成float型,但是没法转换其他的字符串。
>>> float('123') 123.0 >>> float('nan') nan >>> float('nana') Traceback (most recent call last): File "<pyshell#97>", line 1, in <module> float('nana') ValueError: could not convert string to float: 'nana' |
7
hahastudio 2014-08-17 16:45:23 +08:00 1
啊,Python 喜欢先试,后果另说
你大可以 try: ....n = float(input_str) # e.g. input_str = "123" except ValueError: ....n = float("nan") # or any other default value you want 对了,作为豆知识 >>> float("inf") inf >>> float("-inf") -inf 对了,突然想起来,也许这个才是 LZ 最想要的: >>> from decimal import * >>> setcontext(ExtendedContext) >>> nan = Decimal("I'm not a number!") >>> nan Decimal('NaN') >>> print nan NaN 它还能做到更多: >>> inf = Decimal(1) / Decimal(0) >>> print inf Infinity >>> neginf = Decimal(-1) / Decimal(0) >>> print neginf -Infinity >>> print inf + neginf NaN >>> print inf * neginf -Infinity >>> print 2 * inf Infinity >>> print 1 + nan NaN |
8
ZzFoo OP @hahastudio 刚看了一下手册,发现Decimal类有一个is_nan()的方法。谢谢啦~
>>> Decimal('anything').is_nan() True >>> Decimal(1).is_nan() False |