在python中以列方式打印数组

时间:2014-08-06 14:04:41

标签: python

我正在尝试添加如下所示的数组

#       N                     Mn                 Fe                x              x2
3.94870000e+01      -1.22950000e-07     -1.65130000e-05     6.40000000e-01      0.00000000e+00
3.95040000e+01      -9.38580000e-07     -1.63070000e-05     6.41000000e-01      0.00000000e+00
3.95130000e+01      -1.67100000e-06     -1.59280000e-05     6.42000000e-01      0.00000000e+00
3.95230000e+01      -2.29230000e-06     -1.53800000e-05     6.43000000e-01      0.00000000e+00

我设法编写的代码确实添加了列MnFe,但尚未设法将其写入列中:

# N      Mn    Fe  Res

我写的代码是:

#!/usr/bin/env python3
# encoding: utf-8

import numpy as np

inp = "ec.dat"
out = "ec2.dat"


N, Mn, Fe, x, x2 = np.loadtxt(inp, unpack=True)
res = Mn+Fe
print(N, res)
# with open("ec2.dat", 'a') as outfile:

有人会帮我写好桌子吗? 的问候,

编辑 @Paul,谢谢。完整的代码现在是:

#!/usr/bin/env python3
# encoding: utf-8

import numpy as np

inp = "ec.dat"
out = "ec2.dat"


N, Mn, Fe, x, x2 = np.loadtxt(inp, unpack=True)
res = Mn+Fe
with open("ec2.dat", "w") as of:
    for n, mn, fe, res in zip(N, Mn, Fe, res):
        s = "%e %e\n" % (n, res)
        of.write(s)

1 个答案:

答案 0 :(得分:2)

我不会将答案放在一起,而是会向您展示各个部分,以便您自己完成这些工作。

要同时迭代多个numpy数组,您可以执行以下操作:

for n, mn, fe, result in zip(N, Mn, Fe, res):
    print "" + str(n) + " " + str(mn) +" " + str(fe) + " " + str(result)

但是,要执行所需的格式设置,您应该使用字符串说明符:https://docs.python.org/2/library/string.html#format-specification-mini-language

一个例子就像是

v = 1000.526
s = "%e   %e\n" % (10.25, v)
print s

写入文件就像执行:

一样简单
s = "Here is a line I will write to my file\n"
with open("ec2.dat", 'a') as outfile:
    outfile.write(s)

将这些内容链接在一起,您应该能够将所需的输出打印到屏幕或文件中。