输出不同形状数组的索引

2024-09-24 02:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图输出索引及其值。我可以在终端内打印,但我想将其输入到.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.63330999177
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 0.000648636250453 0.632665342501
527 527 2.5 3.1356420 1.0008004 0.0 0 0.000442528552988 0.632611938388


Tags: 文件inimporttxt终端forasrange
1条回答
网友
1楼 · 发布于 2024-09-24 02:16:18

您可以打开一个文件并对其进行写入(请参见此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

相关问题 更多 >