views:

253

answers:

6

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

+1  A: 
#!/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
The MYYN
Why was this downvoted?
Xavier Ho
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.
Colorado
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
inspectorG4dget
thank you for your input, I bugfixed my post ;)
The MYYN
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]=2im really not sure how to word it
robert
try: matrix[0][2] = 2
The MYYN
try working through the python tutorial
John Machin
+4  A: 

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   
unutbu
+3  A: 

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)
gnibbler
A: 

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
badp
A: 
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
mr popo
A: 

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__
orangeoctopus