How to make matrices in Python?

I searched for it and searched for StackOverflow and YouTube .. I just can't get Python matrices to click in my head. Can someone please help me? I'm just trying to create a 5x5 base unit that displays:

AAAAA BBBBB CCCCC DDDDD EEEEE 

I got

 abcde abcde abcde abcde abcde 

To display, but I couldn’t even make them break the lines, instead they would look like

 [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']] 

And if I try to add \ n to them or print "etc., it just doesn’t work. \ N will display as" A \ n ", and print will appear in front of the matrix.

Please help me, even if you direct me somewhere that should be really obvious and make me look like an idiot, I just want to find out.

+7
python matrix
source share
6 answers

Quoting helps:

 for row in matrix: print ' '.join(row) 

or use the nested calls to str.join() :

 print '\n'.join([' '.join(row) for row in matrix]) 

Demo:

 >>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']] >>> for row in matrix: ... print ' '.join(row) ... ABCDE ABCDE ABCDE ABCDE ABCDE >>> print '\n'.join([' '.join(row) for row in matrix]) ABCDE ABCDE ABCDE ABCDE ABCDE 

If you want to show transposed rows and columns, transpose the matrix using the zip() function; if you pass each row as a separate argument to a function, zip() recombines that value by value as column tuples. The syntax *args allows you to apply an entire sequence of strings as separate arguments:

 >>> for cols in zip(*matrix): # transposed ... print ' '.join(cols) ... AAAAA BBBBB CCCCC DDDDD EEEEE 
+9
source share

The answer to your question depends on your learning objectives. If you are trying to get matrices before "click" to use them later, I would suggest looking at the Numpy array instead of a list of lists. This will allow you to easily cut rows and columns and subsets. Just try to get a column from the list of lists and you will be disappointed.

Using the list of lists as a matrix ...

Let's take your list of lists, for example:

 L = [list("ABCDE") for i in range(5)] 

It is easy to get subelements for any row:

 >>> L[1][0:3] ['A', 'B', 'C'] 

Or a whole line:

 >>> L[1][:] ['A', 'B', 'C', 'D', 'E'] 

But try flipping this around to get the same elements in a column format, and that won't work ...

 >>> L[0:3][1] ['A', 'B', 'C', 'D', 'E'] >>> L[:][1] ['A', 'B', 'C', 'D', 'E'] 

You will need to use something like list comprehension to get all the 1st elements ....

 >>> [x[1] for x in L] ['B', 'B', 'B', 'B', 'B'] 

Enter matrices

If you use an array instead, you get the slicing and indexing that you would expect from MATLAB or R (or most other languages, for that matter):

 >>> import numpy as np >>> Y = np.array(list("ABCDE"*5)).reshape(5,5) >>> print Y [['A' 'B' 'C' 'D' 'E'] ['A' 'B' 'C' 'D' 'E'] ['A' 'B' 'C' 'D' 'E'] ['A' 'B' 'C' 'D' 'E'] ['A' 'B' 'C' 'D' 'E']] >>> print Y.transpose() [['A' 'A' 'A' 'A' 'A'] ['B' 'B' 'B' 'B' 'B'] ['C' 'C' 'C' 'C' 'C'] ['D' 'D' 'D' 'D' 'D'] ['E' 'E' 'E' 'E' 'E']] 

Grab line 1 (as in the lists):

 >>> Y[1,:] array(['A', 'B', 'C', 'D', 'E'], dtype='|S1') 

Take column 1 (new!):

 >>> Y[:,1] array(['B', 'B', 'B', 'B', 'B'], dtype='|S1') 

So now to create a printed matrix:

 for mycol in Y.transpose(): print " ".join(mycol) AAAAA BBBBB CCCCC DDDDD EEEEE 
+10
source share

you can also use append function

 b = [ ] for x in range(0, 5): b.append(["O"] * 5) def print_b(b): for row in b: print " ".join(row) 
+2
source share

you can do it like this:

 matrix = [["A, B, C, D, E"]*5] print(matrix) [['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']] 
0
source share

I got a simple fix by dropping lists into strings and performing string operations to get the correct listing from the matrix.

Function Creation

By creating a function, this saves you from having to write a for loop every time you want to print a matrix.

 def print_matrix(matrix): for row in matrix: new_row = str(row) new_row = new_row.replace(',','') new_row = new_row.replace('[','') new_row = new_row.replace(']','') print(new_row) 

Examples

Example 5x5 matrix with 0 as each record:

 >>> test_matrix = [[0] * 5 for i in range(5)] >>> print_matrix(test_matrix) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

An example of a 2x3 matrix with 0 as each record:

 >>> test_matrix = [[0] * 3 for i in range(2)] >>> print_matrix(test_matrix) 0 0 0 0 0 0 

EDIT

If you want to print:

 AAAAA BBBBB CCCCC DDDDDEEEEE 

I suggest you just change the way you enter your data into your lists in lists. In my method, each list in a larger list is a row in the matrix, not columns.

0
source share

If you do not want to use numpy, you can use the concept of a list of lists. To create any 2D array, simply use the following syntax:

  mat = [[input() for i in range (col)] for j in range (row)] 

and then enter the desired values.

0
source share

All Articles