TL; DR:
- 如果您输入的大部分内容都是可以转换为浮点数的字符串,则该
try: except:
方法是最好的本机Python方法。
- 如果您的输入大部分是不能输入的字符串转换为浮点数的,则正则表达式或partition方法会更好。
- 如果您1)不确定您的输入或需要更快的速度,并且2)不介意并可以安装第三方C扩展名,则fastnumbers效果很好。
通过第三方模块可以使用另一种称为fastnumbers的方法(公开,我是作者)。它提供了一个称为isfloat的功能。我在这个答案中采用了Jacob Gabrielson概述的单元测试示例,但是添加了该fastnumbers.isfloat
方法。我还应该注意,Jacob的示例对正则表达式选项不公道,因为该示例中的大多数时间都因为点运算符而花费在全局查找中try: except:
。
def is_float_try(str):
try:
float(str)
return True
except ValueError:
return False
import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$").match
def is_float_re(str):
return True if _float_regexp(str) else False
def is_float_partition(element):
partition=element.partition('.')
if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
return True
else:
return False
from fastnumbers import isfloat
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests(unittest.TestCase):
def test_re_perf(self):
print
print 're sad:', timeit.Timer('ttest.is_float_re("12.2x")', "import ttest").timeit()
print 're happy:', timeit.Timer('ttest.is_float_re("12.2")', "import ttest").timeit()
def test_try_perf(self):
print
print 'try sad:', timeit.Timer('ttest.is_float_try("12.2x")', "import ttest").timeit()
print 'try happy:', timeit.Timer('ttest.is_float_try("12.2")', "import ttest").timeit()
def test_fn_perf(self):
print
print 'fn sad:', timeit.Timer('ttest.isfloat("12.2x")', "import ttest").timeit()
print 'fn happy:', timeit.Timer('ttest.isfloat("12.2")', "import ttest").timeit()
def test_part_perf(self):
print
print 'part sad:', timeit.Timer('ttest.is_float_partition("12.2x")', "import ttest").timeit()
print 'part happy:', timeit.Timer('ttest.is_float_partition("12.2")', "import ttest").timeit()
unittest.main()
在我的机器上,输出为:
fn sad: 0.220988988876
fn happy: 0.212214946747
.
part sad: 1.2219619751
part happy: 0.754667043686
.
re sad: 1.50515985489
re happy: 1.01107215881
.
try sad: 2.40243887901
try happy: 0.425730228424
.
----------------------------------------------------------------------
Ran 4 tests in 7.761s
OK
如您所见,regex实际上并不像最初看起来的那样糟糕,并且如果您确实对速度有需求,则此fastnumbers
方法相当不错。