在Python中按列打印数组

0 投票
1 回答
1306 浏览
提问于 2025-04-18 16:15

我正在尝试添加一个数组,如下所示:

#       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 个回答

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)

把这些东西连接起来,你就能把想要的输出打印到屏幕上或者写入文件了。

撰写回答