总结/评估现有的方法:
Candidate | type | delnan | mat | shrewmouse | ant6n ------------------------------------------------------------------------- 0 | <type 'int'> | 1 | 1 | 1 | 1 0.0 | <type 'float'> | 1 | 1 | 1 | 1 0j | <type 'complex'> | 1 | 1 | 1 | 0 Decimal('0') | <class 'decimal.Decimal'> | 1 | 0 | 1 | 1 True | <type 'bool'> | 1 | 1 | 1 | 1 False | <type 'bool'> | 1 | 1 | 1 | 1 '' | <type 'str'> | 0 | 0 | 0 | 0 None | <type 'NoneType'> | 0 | 0 | 0 | 0 '0' | <type 'str'> | 0 | 0 | 0 | 1 '1' | <type 'str'> | 0 | 0 | 0 | 1 [] | <type 'list'> | 0 | 0 | 0 | 0 [1] | <type 'list'> | 0 | 0 | 0 | 0 [1, 2] | <type 'list'> | 0 | 0 | 0 | 0 (1,) | <type 'tuple'> | 0 | 0 | 0 | 0 (1, 2) | <type 'tuple'> | 0 | 0 | 0 | 0
(我是这个问题来的 )
码
#!/usr/bin/env python """Check if a variable is a number.""" import decimal def delnan_is_number(candidate): import numbers return isinstance(candidate, numbers.Number) def mat_is_number(candidate): return isinstance(candidate, (int, long, float, complex)) def shrewmouse_is_number(candidate): try: return 0 == candidate * 0 except: return False def ant6n_is_number(candidate): try: float(candidate) return True except: return False # Test candidates = (0, 0.0, 0j, decimal.Decimal(0), True, False, '', None, '0', '1', [], [1], [1, 2], (1, ), (1, 2)) methods = [delnan_is_number, mat_is_number, shrewmouse_is_number, ant6n_is_number] print("Candidate | type | delnan | mat | shrewmouse | ant6n") print("-------------------------------------------------------------------------") for candidate in candidates: results = [m(candidate) for m in methods] print("{:<12} | {:<25} | {:>6} | {:>3} | {:>10} | {:>5}" .format(repr(candidate), type(candidate), *results))