【问题标题】:Separate float into digits将浮点数分隔为数字
【发布时间】:2015-04-21 11:06:18
【问题描述】:

我有一个花车:

pi = 3.141

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

#[3, 1, 4, 1]

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

【问题讨论】:

  • How is PI calculated? 的可能重复项
  • 浮点数并不是真正的十进制数字,它具有二进制数字,您的pi 的十进制数字同样可以是3.1410000000000000142108547152020037174224853515625
  • (试试'%.100f' % 3.141

标签: python string list


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 我尝试了brite force方法,因为我没有理解你显示的其他两个,但列表仍然是字符串列表而不是整数:x = list(str(number)) x.remove ('.') map(int,x) return x (number is pi) result: ['3', '1', '4', '1', '5', '9', '2', ' 6', '5', '3', '5', '9']
  • @JoJo 我确定你错过了最后一个声明。那是map(int,x)
【解决方案2】:

您还可以将string.replacemaplist 函数一起使用。

>>> s = 3.141
>>> list(map(int, str(s).replace('.','')))
[3, 1, 4, 1]

【讨论】:

  • 我认为这是因为您的代码检查每个字符是否为数字。
猜你喜欢
  • 1970-01-01
  • 2020-09-02
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多