python - 不同形状数组的输出索引 Python

标签 python arrays numpy

我正在尝试输出索引及其值。我可以在终端中打印它,但我想将其输入到 .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/

相关文章:

python - 点击模块的单元测试

Python Win32 扩展不可用?

opencv - FFTPACK Scipy 全局名称未正确定义。怎么修?

python - 从python中的n个子数组副本创建一个数组

Python 2.7 JSON 转储 UnicodeEncodeError

python - 将 Sublime 与 virtualenv 结合使用

PHP 数组 stdClass 对象 - 回显值

c# - 如何使用 AutoMapper 从可枚举(或数组)列表属性映射到列表?

javascript - 从用逗号分隔的对象中收集数据并将其作为单独的对象 - Javascript

python - 向量化 numpy 代码