gpt4 book ai didi

Python 格式化 : How to insert blank spaces in between array data elements of data type float

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:09 25 4
gpt4 key购买 nike

我有一个关于格式的问题。我正在尝试提取相关数据并将这些数据插入到 Fortran 文件中。值得庆幸的是,我正在使用 python 来完成这项任务。碰巧的是,fortran 文件对文本之间的空格数很敏感。所以,这让我想到了我的问题。我的数组数组数据如下所示:

    [[ -1.80251269  12.14048223  15.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[-14.80251269 1.14048223 1.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[ -0.80251269 0.14048223 0.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]

这些元素是 float ,不是字符串。例如,我希望数据的第一行(以及之后的每一行)看起来像:

     -1.80251269     12.14048223     15.47522331

我将如何做到这一点?具体来说,有 5 个空格将左边距与第一个数字 -1.80251269 分隔开,还有 5 个空格分隔三个数字中的每一个。另请注意,我需要去掉数组括号,但我怀疑我可以使用 trim 函数来完成此操作。对不起,我缺乏知识,伙计们;我什至不知道如何开始这个问题,因为我对 Python 语法的了解有限。任何帮助或提示将不胜感激。谢谢!

编辑:这是我用来生成数组的代码:

     fo = np.genfromtxt("multlines.inp")
data=scipy.delete(fo, 0, 1)
txt = np.hsplit(data,3)
all_data = np.vsplit(data, 4)
i=0
num_molecules = int(raw_input("Enter the number of molecules: "))
print "List of unaltered coordinates:"
while i < (num_molecules):
print all_data[i]

最佳答案

如果你使用的是 NumPy,你可以使用 np.savetxt:

np.savetxt('a.txt', a.reshape(15,3), '%16.8f')

得到

     -1.80251269      12.14048223      15.47522331
-2.63865822 13.16562850 15.97462801
-1.76966256 11.35311123 16.13958474
...

(您需要将数组 reshape 为 2 维才能执行我认为您想要的操作)。

关于Python 格式化 : How to insert blank spaces in between array data elements of data type float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com