python - 将 float 分隔成数字

标签 python string list

我有一个花车:

pi = 3.141

并且想要将 float 的数字分开并将它们作为整数放入列表中,如下所示:

#[3, 1, 4, 1]

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

最佳答案

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

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

另一种使用 Regex 的方法(不推荐)

>>> 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

如您所见,蛮力法是最快的。已知的 Regex 答案是最慢的。

关于python - 将 float 分隔成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29770437/

相关文章:

python - 如何从经过训练的 Tensorflow 分类器获得类别预测?

php - 在 Python 中替换字符串时可以传递字典吗?

c - 打印列表 : 1 2 3 4 5 6 7 8 9 = 1 8 3 6 5 4 7 2 9

python - 索引错误: list assignment index out of range in Python

Python 不会跳过 "if [strg] or [strg] in variable"

Python:iter(x) 是否等同于 for el in x: yield el?

javascript - 在javascript不起作用的字符串中使字符大写

java - 错误的拆分字符串(拆分 (""))

c# - C#中字符串开头的 `@`是什么意思?

python - 索引列表的第一个和最后一个元素