简体   繁体   English

如何在Python 3中迭代浮点数?

[英]How to iterate a float in Python 3?

So now I have a variable which is x = 1001.0010101 所以现在我有一个变量x = 1001.0010101

From this x, I wanna separate into two parts: 从这个x,我想分为两部分:

x = 1001.0010101
val_int = int(x)                         #get val_int   = 1001
val_fract = {0:.5f}".format(a - val_int) #get val_fract = 0.00101

Is it possible to use for loop to iterate the val_fract to be like: (ignore the int part and decimal point) 是否可以使用for循环将val_fract迭代为:(忽略int部分和小数点)

0 
0 
1 
0 
1

I have tried so many times and I couldn't get it done and the system told me 我已经尝试了很多次,但无法完成,系统告诉我

Traceback (most recent call last):
  File "python", line 46, in <module>
TypeError: 'float' object is not iterable

Thanks for your help, much appreciated. 感谢您的帮助,不胜感激。

You can use math module in python to separate decimal and integer part 您可以在python中使用math模块来分隔小数和整数部分

import math 
x = 1001.0010101
math.modf(x)
#output:(0.0010101000000304339, 1001.0)

Iterate as you want 根据需要迭代

Have doubt about extra numbers in end of decimal read docs 对十进制末尾的额外数字有疑问的文档

I don't know, why you suggest in your comment that leading zeros are missing: 我不知道,为什么您在评论中建议缺少前导零:

x = 1001.0010101
#separate fractional from integer part
frac = str(x).split(".")

for digit in frac[1]:
    print(digit)

Alternatively, you can transform both parts into lists of integers: 或者,您可以将两个部分都转换为整数列表:

#integer digits
x_int = list(map(int, frac[0]))
#fractional digits
x_frac = list(map(int, frac[1]))
x = 1001.0010101
x = "{0:.5f}".format(x)
for i in str(x).split(".")[1]:
    print(i)

Output : 输出

0
0
1
0
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM