我正在解析一个文件,该文件包含由空格分隔的浮点行,格式为:+/-0.XXXE-8,在读取 float 并将它们保存在列表中时,它会更改为+/-X.XXXE-9。
我想做的是将数字打印为+/-0.XXXE-8(与我读到的格式相同),但没有运气。
输入文件中的示例行是:
0.43578E-08 0.48992E-08 0.54452E-08 0.59816E-08 0.64918E-08 0.69577E-08
读取该行后打印该行的输出:
4.357800e-09 4.899200e-09 5.445200e-09 5.981600e-09 6.491800e-09 6.957700e-09
有没有办法将任何 float 转换为0.XXXE-8,无论数字是什么,例如:
x = 1.3E-9
print(func(x)) -> 0.13E-8
希望得到一些帮助
谢谢
最佳答案
您已经意识到这些数字在数字上是相同的。
所以这只是一个显示问题,您可以通过自己格式化它们来解决:
data = [0.43578E-08, 0.48992E-08, 0.54452E-08, 0.59816E-08, 0.64918E-08, 0.69577E-08]
def format_float_weirdly(myfloat):
"""Formats a float to 0.xxxxxxxe-08 if it would be presened as x.xxxxxxe-09
when normally formatted. If not, the normal format is outputted."""
float_String = f"{myfloat:.8n}"
if float_String[1] == "." and float_String.endswith("e-09"):
float_String = "0." + float_String.replace(".","").replace("e-09","e-08")
return float_String
d2 = [format_float_weirdly(f) for f in data]
print(data)
print(d2)
输出:
# printout of data
[4.3578e-09, 4.8992e-09, 5.4452e-09, 5.9816e-09, 6.4918e-09, 6.9577e-09]
['0.43578e-08', '0.48992e-08', '0.54452e-08', '0.59816e-08', '0.64918e-08', '0.69577e-08']
您可以通过对“正常字符串表示”进行一些数学和字符串切片来调整它以适应“任何”其他表示。据我所知,没有内置方法可以像您想要的那样“格式化” float normal string formatting意思是。
关于python-3.x - 如何将浮点转换为任何浮点的 XE-Y 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983222/