【问题标题】:Using numpy to write an array to stdout使用 numpy 将数组写入标准输出
【发布时间】:2014-04-26 06:26:10
【问题描述】:

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

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 )

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

【问题讨论】:

    标签: python arrays python-3.x numpy stdout


    【解决方案1】:

    下面的代码怎么样?

    >>> 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, ...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-19
      • 2010-10-17
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      相关资源
      最近更新 更多