我正在尝试输出索引及其值。我可以在终端中打印它,但我想将其输入到 .txt 文件中。这是我目前拥有的代码。我认为提及 x&y 的形状 (528,) 以及其余的形状 (528, 528) 会很有帮助。我当前的输出也在代码部分之后。
import pencil as pc
import numpy as np
ff = pc.read_var(trimall=True)
x = ff.x
y = ff.y
rho = ff.rho
rhop = ff.rhop
ux = ff.ux
uy = ff.uy
for i in range(528):
for j in range(528):
print i,j,rho[i,j],rhop[i,j],ux[i,j],uy[i,j]
我看到的输出是这样的,这正是我想要的,但写入了 .txt 文件。
527 524 2.5 3.0999421 1.0025754 3.14249721489 0.00104948277254 0.633309939177
527 525 2.5 3.1118420 1.0046337 0.0 0.000712933516338 0.632900900838
527 526 2.5 3.1237420 1.0032471 0.0 0.000648636250453 0.632665342501
527 527 2.5 3.1356420 1.0008004 0.0 0.000442528552988 0.632611938388
最佳答案
您可以打开文件并向其写入(请参阅此 Python tutorial ):
with open("output.txt", "w") as fout:
for i in range(528):
for j in range(528):
fout.write("%d %d %f %f %f %f\n" % (i,j,rho[i,j],rhop[i,j],ux[i,j],uy[i,j]))
或者,只需运行脚本并将输出通过管道传输到文件:
python script.py >output.txt
关于python - 不同形状数组的输出索引 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44853513/