1

While there are a few questions and answers out there which come close to what I am looking for, I am wondering if there isn't a more elegant solution to this specific problem: I have a numpy (2D) array and want to print it row by row together with the row number up front - and of course nicely formatted.

This code does the printing, straightforward but without formatting:

import numpy as np
A = np.zeros((2,3))
for i in range(2):
    print i, A[i]

I can also produce formatted output by building the formatted string anew in each line:

for i in range(2):
    print "%4i "%(i)+" ".join(["%6.2f"%(v) for v in A[i]])

While this works, I figured it may be more readable and perhaps more efficient(?) to build the format string only once and then "paste" the numbers in for each line:

NVAR=A.shape[1]
fmt = "%4i" + NVAR*"  %6.2f"
for i in range(2):
    print fmt % (i, A[i])

This fails, because the formatted print expects a tuple with float elements, but A[i] is an ndarray. Thus, my questions really boils down to "How can I form a tuple out of an integer value and a 1-D ndarray?". I did try:

    tuple( [i].extend([v for v in A[i]]) )

but that doesn't work (this expression yields None, even though [v for v in A[i]] works correctly).

Or am I only still too much thinking FORTRAN here?

4

3 回答 3

1

tuple您可以使用构造函数将数组元素直接转换为元组:

for i in range(2):
    print fmt % ((i, ) + tuple(A[i]))

这里,+表示元组连接。

此外,如果您来自 FORTRAN,您可能还不知道enumerate,这对于这种类型的循环操作可能很方便:

for i, a in enumerate(A):
    print fmt % ((i, ) + tuple(a))

您可以将其与itertools.chainenumerate 中的对展平:

import itertools

for i, a in enumerate(A):
    print fmt % tuple(itertools.chain((i, ), a))

对于您在这里尝试做的事情,这些都可能是矫枉过正,但我​​只是想展示更多的方法。

于 2013-09-08T17:09:36.107 回答
1

您可以先将 numpy 数组转换为列表tolist()

for i in range(2):
    print fmt % tuple([i] + A[i].tolist())

您的错误的原因是扩展列表不会产生返回值。

>>> x = range(5)
>>> x.extend([5, 6])
>>> x
[0, 1, 2, 3, 4, 5, 6]

+运算符用于连接列表。

于 2013-09-07T20:14:09.400 回答
0

这是一个简单的解决方案:

import numpy as np
A = np.random.rand(200,3)
for i in xrange(98, 102):
    print '{0:4d} {1}'.format(i, A[i]) #'4d' reserves space for 4 digits
                                       # Modify to the maximum # of rows

输出如下所示:

  98 [ 0.40745341  0.29954899  0.21880649]
  99 [ 0.23325155  0.81340095  0.57966024]
 100 [ 0.24145552  0.12387366  0.0384011 ]
 101 [ 0.76432552  0.68382022  0.93935336]
于 2013-09-09T19:43:24.110 回答