<p>这将为您提供一个很好的对齐输出。你知道吗</p>
<pre><code>from numpy import random, cos, sin, sqrt, pi
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def rand_sphere(n):
z = 2 * random.rand(n) - 1 # uniform in -1, 1
t = 2 * pi * random.rand(n) # uniform in 0, 2*pi
x = sqrt(1 - z**2) * cos(t)
y = sqrt(1 - z**2) * sin(t)
return x, y, z
def col_align(x, y, z):
data = '{:>3} {:>6} {:>6} {:>6}\n'.format('m', 'x', 'y', 'z')
for i in range(len(x)):
data += '{: 3d} {: 05.3f} {: 05.3f} {: 05.3f}\n'.format(10, x[i], y[i], z[i])
return data
x, y, z = rand_sphere(200)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
plt.savefig('sphere.png')
plt.show()
Outfile=open('output.txt','w')
Outfile.write('This line will be text\n')
Outfile.write('\n')
Outfile.write(col_align(x, y, z))
Outfile.close()
</code></pre>
<p>我只是使用了你的脚本,在编写文件之前对格式输出进行了一些处理。在这里<a href="https://pyformat.info/" rel="nofollow noreferrer">https://pyformat.info/</a>查看有关格式化字符串方法的详细信息,以防您希望调整浮点精度和空格以满足您的需要。你知道吗</p>
<p>仅供参考,以下是我的<code>output.txt</code>文件的第一行:</p>
<pre><code>This line will be text
m x y z
10 0.554 -0.826 0.105
10 -0.501 -0.816 -0.287
10 -0.774 -0.515 -0.368
10 -0.537 0.672 -0.510
10 0.869 0.291 0.401
10 -0.511 0.806 0.299
10 0.488 -0.770 -0.412
</code></pre>