将浮点数分开 [英] Separate float into digits

查看:125
本文介绍了将浮点数分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮游物:

pi = 3.141

并想将浮点数字分开,并以如下整数形式将它们放入列表中:

And want to separate the digits of the float and put them into a list as intergers like this:

#[3, 1, 4, 1]

我知道将它们分开并放在列表中,但是作为字符串,这对我没有帮助

I know to to separate them and put them into a list but as strings and that doesnt help me

推荐答案

您需要遍历数字的字符串表示形式,并检查数字是否为数字.如果是,则将其添加到列表中.这可以通过使用列表理解来完成.

You need to loop through the string representation of the number and check if the number is a digit. If yes, then add it to the list. This can be done by using a list comprehension.

>>> pi = 3.141
>>> [int(i) for i in str(pi) if i.isdigit()]
[3, 1, 4, 1]

使用正则表达式的另一种方式(不推荐)

Another way using Regex (Not - preffered)

>>> map(int,re.findall('\d',str(pi)))
[3, 1, 4, 1]

最后的方法-蛮力

>>> pi = 3.141
>>> x = list(str(pi))
>>> x.remove('.')
>>> map(int,x)
[3, 1, 4, 1]

文档中的参考文献很少

timeit结果

python -m timeit "pi = 3.141;[int(i) for i in str(pi) if i.isdigit()]"
100000 loops, best of 3: 2.56 usec per loop
python -m timeit "s = 3.141; list(map(int, str(s).replace('.','')))" # Avinash's Method
100000 loops, best of 3: 2.54 usec per loop
python -m timeit "import re;pi = 3.141; map(int,re.findall('\d',str(pi)))"
100000 loops, best of 3: 5.72 usec per loop
python -m timeit "pi = 3.141; x = list(str(pi));x.remove('.'); map(int,x);"
100000 loops, best of 3: 2.48 usec per loop

如您所见,蛮力方法是最快的.正则表达式的答案是最慢的.

As you can see the brute force method is the fastest. The Regex answer as known is the slowest.

这篇关于将浮点数分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆