user1692261
user1692261

Reputation: 1217

print matrix with indicies python

I have a matrix in Python defined like this:

matrix = [['A']*4 for i in range(4)]

How do I print it in the following format:

   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A

Upvotes: 2

Views: 26178

Answers (5)

nn0p
nn0p

Reputation: 1209

Use pandas for showing any matrix with indices:

>>> import pandas as pd
>>> pd.DataFrame(matrix)
   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

Something like this:

>>> matrix = [['A'] * 4 for i in range(4)]
>>> def solve(mat):
    print " ", " ".join([str(x) for x in xrange(len(mat))])
    for i, x in enumerate(mat):
        print i, " ".join(x)  # or " ".join([str(y) for y in x]) if elements are not string
...         
>>> solve(matrix)
  0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A'] * 5 for i in range(5)]
>>> solve(matrix)
  0 1 2 3 4
0 A A A A A
1 A A A A A
2 A A A A A
3 A A A A A
4 A A A A A

Upvotes: 2

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

This function matches your exact output.

>>> def printMatrix(testMatrix):
        print ' ',
        for i in range(len(testMatrix[1])):  # Make it work with non square matrices.
              print i,
        print
        for i, element in enumerate(testMatrix):
              print i, ' '.join(element)
>>> matrix = [['A']*4 for i in range(4)]
>>> printMatrix(matrix)
  0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A']*6 for i in range(4)]
>>> printMatrix(matrix)
  0 1 2 3 4 5
0 A A A A A A
1 A A A A A A
2 A A A A A A
3 A A A A A A

To check for single length elements and put an & in place of elements with length > 1, you could put a check in the list comprehension, the code would change as follows.

>>> def printMatrix2(testMatrix):
    print ' ',
    for i in range(len(testmatrix[1])):
        print i,
    print
    for i, element in enumerate(testMatrix):
        print i, ' '.join([elem if len(elem) == 1 else '&' for elem in element])
>>> matrix = [['A']*6 for i in range(4)]
>>> matrix[1][1] = 'AB'
>>> printMatrix(matrix)
  0 1 2 3 4 5
0 A A A A A A
1 A AB A A A A
2 A A A A A A
3 A A A A A A
>>> printMatrix2(matrix)
  0 1 2 3 4 5
0 A A A A A A
1 A & A A A A
2 A A A A A A
3 A A A A A A

Upvotes: 1

Muhammed Rafi CH
Muhammed Rafi CH

Reputation: 1

a=[["A" for i in range(4)] for j in range(4)]

for i in range(len(a)):
  print()
  for j in a[i]:
     print("%c "%j,end='')

it will print like this:

A A A A
A A A A
A A A A
A A A A

Upvotes: 0

icecrime
icecrime

Reputation: 76745

>>> for i, row in enumerate(matrix):
...     print i, ' '.join(row)
...
0 A A A A
1 A A A A
2 A A A A
3 A A A A

I guess you'll find out how to print out the first line :)

Upvotes: 2

Related Questions