0

I have a

a=[[1,2,3],[4,5,6],[7,8,9]]

I want to print "a" the a like matrix form however like columnwise :

 1 4 7 
 2 5 8
 3 6 9

Is there any way to do this?

user741592
  • 875
  • 3
  • 10
  • 25

4 Answers4

4

You can transpose it using zip:

print zip(*a)
>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

It should work for any shape, not only square matrix. The only situation it gives dodgy result is when a has one row.

You can print it in your desired form using join:

for el in a:
    print " ".join(str(s) for s in el)

Or, as suggested by @ssm, a one-liner:

print '\n'.join(' '.join(map(str,x)) for x in zip(*a))

And finally, using numpy:

print '\n'.join(' '.join(map(str,x)) for x in np.transpose(a))
sashkello
  • 17,306
  • 24
  • 81
  • 109
  • Also, it needs to be converted to string like so: `'\n'.join( [' '.join(map(str,x)) for x in zip(*a)] )`. Good use of the zip(*)! – ssm Mar 14 '14 at 05:45
2

If you just want to print, you can do the following, although I do assume that the matrix is rectangular.

a=[[1,2,3],[4,5,6],[7,8,9]]

for i in xrange(len(a[0])):
   print " ".join(str(a[j][i]) for j in xrange(len(a)))
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

You can print a row-major matrix like this:

def print_row_maj(m):
    for row in m:
       print ' '.join(str(x) for x in row)

Combine this with sashkello's answer to print your transposed (not inverted!) matrix.

def transpose(m):
    return zip(*m)

a=[[1,2,3],[4,5,6],[7,8,9]]    

print_row_maj( transpose(a) )
Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0
var arrnew = new Array();
arrnew = [[2, 3, 4], [4, 5, 7], [5, 6, 9]];

for (var i = 0; i < arrnew.length; i++) {
console.log(arrnew[i][0] + " " + arrnew[i][1] + " " + arrnew[i][2]);

}

Amul Harad
  • 148
  • 4