python - 使用 numpy 将数组写入标准输出

标签 python arrays python-3.x numpy stdout

将 Numpy 二维数组写入标准输出的惯用方法是什么?例如我有一个数组

a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]])

[[ 2.  0.  0.]
 [ 0.  2.  0.]
 [ 0.  0.  4.]]

我希望输出为:

2.0 0.0 0.0
0.0 2.0 0.0
0.0 0.0 4.0

我可以通过转换为嵌套列表,然后加入列表元素来做到这一点:

print( '\n'.join( [ ' '.join( [ str(e) for e in row ] ) for row in a.tolist() ] ) )

但是想要这样的东西:

a.tofile( sys.stdout )

(除非这给出了语法错误)。

最佳答案

下面的代码怎么样?

>>> a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]])
>>> numpy.savetxt(sys.stdout, a, fmt='%.4f')
1.0000 2.0000 3.0000
0.0000 2.0000 0.0000
0.0000 0.0000 4.0000

在 Python 3+ 中,使用 numpy.savetxt(sys.stdout.buffer, ...)

关于python - 使用 numpy 将数组写入标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515522/

相关文章:

python - 在Python中测量多线程代码的处理时间

python - 我无法处理列表中的键

javascript - 未捕获的类型错误无法读取未定义 Javascript 的属性 '0'

python - 如何处理大量小部件的 QPropertyAnimation

Python 正则表达式 - 去除开始和结束并保持中间不变

python - 在 python 中,如果我对复杂数据执行 fft,然后仅对正频率进行 irfft,这对数据有何影响?

jquery - JS jQuery - 检查值是否在数组中

用于向量化函数的 Python 和 Numba

python - python 中的作用域规则

python - ModelForm 中的 Django 查询集使用 'pk'