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?
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?
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))
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)))
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) )
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]);
}