0

say ive got a matrix that looks like:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

how can i make it on seperate lines:

[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]

and then remove commas etc:

0 0 0 0 0

And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like:

_ 1 2 _ 1 _ 1

(spaces not underscores)

thanks

2
  • 7
    You do realize that what you have is a list containing 3 lists, each containing 5 0's - your data structure does not "contain" any commas or brackets or punctuation to be "removed"; these are merely artifacts of the representation format for a list of lists. You might as well ask how to remove the period from the value of pi.
    – PaulMcG
    May 30, 2010 at 3:38
  • By the way, the second example is valid Python.
    – badp
    May 30, 2010 at 12:41

6 Answers 6

4

This allocates 4 spaces for each number in the matrix. You may have to adjust this depending on your data of course.

This also uses the string format method introduced in Python 2.6. Ask if you'd like to see how to do it the old way.

matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in matrix:
    data=(str(num) if num else ' ' for num in row])   # This changes 0 to a space
    print(' '.join(['{0:4}'.format(elt) for elt in data]))

yields

     1    2             
     1                  
20                  1   
3

Here is a shorter version of ~untubu's answer

M = [[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in M:
    print " ".join('{0:4}'.format(i or " ") for i in row)
1
#!/usr/bin/env python

m = [[80, 0, 3, 20, 2], [0, 2, 101, 0, 6], [0, 72 ,0, 0, 20]]

def prettify(m):
    for r in m:
        print ' '.join(map(lambda e: '%4s' % e, r)).replace(" 0 ", "   ")

prettify(m)

# => prints ...
# 80         3   20    2
#       2  101         6
#      72             20
3
  • This will replace any zero with a space, not just 0. Numbers like 10 and 102 are in trouble. Unless you can guarantee the values will only be single digits, this isn't a good solution.
    – exupero
    May 30, 2010 at 4:00
  • Nice catch @EShull. I saw something similar - what happens if there are values in the matrix that require more than just one digit? Aside from @EShull's problem, there's also the problem of proper alignment May 30, 2010 at 4:30
  • tyvm for the help guys, but would you know how i would change it to add 1's and 2's into it at certain places. Im trying to make a kind of basic version of connect-4, and going to use 1's and 2's for the players chips in it. would it be something along the lines of: matrix.append[0][2]=2 im really not sure how to word it
    – robert
    May 30, 2010 at 4:44
1

This answer also calculates the appropriate field length, instead of guessing 4 :)

def pretty_print(matrix):
  matrix = [[str(x) if x else "" for x in row] for row in matrix]
  field_length = max(len(x) for row in matrix for x in row)
  return "\n".join(" ".join("%%%ds" % field_length % x for x in row)
                   for row in matrix)

There is an iteration too much here, so if performance in critical you'll want to do the initial str() pass and field_length calculation in a single non-functional loop.

>>> matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 1, 1, 1, 0.30314]]
>>> print pretty_print(matrix)
              1       2                
              1                        
     20       1       1       1 0.30314
>>> matrix=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> print pretty_print(matrix)
1    
  1  
    1
0
def matrix_to_string(matrix, col):
        lines = []
        for e in matrix:
            lines.append(str(["{0:>{1}}".format(str(x), col) for x in e])[1:-1].replace(',','').replace('\'',''))
        pattern = re.compile(r'\b0\b')
        lines = [re.sub(pattern, ' ', e) for e in lines]
        return '\n'.join(lines)

Example:

matrix = [[0,1,0,3],[1,2,3,4],[10,20,30,40]]
print(matrix_to_string(matrix, 2))

Output:

    1     3
 1  2  3  4
10 20 30 40
0

If you are doing a lot with matrices, I strongly suggest using numpy (3rd party package) matrix. It has a lot of features that are annoying to do with iteration (e.g., scalar multiplication and matrix addition).

http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html

Then, if you want to make "print" output your particular format, just inherit from numpy's matrix and replace the repr and str methods with some of the solutions presented by the others here.

class MyMatrix(numpy.matrix):
   def __repr__(self):
      repr = numpy.matrix.__repr__(self)

      ...

      return pretty_repr

   __str__ = __repr__

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.