I\'ve googled it and searched StackOverflow and YouTube.. I just can\'t get matrices in Python to click in my head. Can someone please help me? I\'m just trying to create a
The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy array
instead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lists and you will be frustrated.
Let's take your list of lists for example:
L = [list("ABCDE") for i in range(5)]
It is easy to get sub-elements for any row:
>>> L[1][0:3]
['A', 'B', 'C']
Or an entire row:
>>> L[1][:]
['A', 'B', 'C', 'D', 'E']
But try to flip that around to get the same elements in column format, and it won't work...
>>> L[0:3][1]
['A', 'B', 'C', 'D', 'E']
>>> L[:][1]
['A', 'B', 'C', 'D', 'E']
You would have to use something like list comprehension to get all the 1th elements....
>>> [x[1] for x in L]
['B', 'B', 'B', 'B', 'B']
If you use an array instead, you will get the slicing and indexing that you 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 row 1 (as with lists):
>>> Y[1,:]
array(['A', 'B', 'C', 'D', 'E'],
dtype='|S1')
Grab column 1 (new!):
>>> Y[:,1]
array(['B', 'B', 'B', 'B', 'B'],
dtype='|S1')
So now to generate your printed matrix:
for mycol in Y.transpose():
print " ".join(mycol)
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
I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.
By creating a function, it saves you the trouble of writing the for
loop every time you want to print out 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)
Example of a 5x5 matrix with 0
as every entry:
>>> 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
Example of a 2x3 matrix with 0
as every entry:
>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0
If you want to make it print:
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
I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.
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)
you can do it short 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']]
Looping helps:
for row in matrix:
print ' '.join(row)
or use nested str.join()
calls:
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)
...
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 '\n'.join([' '.join(row) for row in 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
If you wanted to show the rows and columns transposed, transpose the matrix by using the zip() function; if you pass each row as a separate argument to the function, zip()
recombines these value by value as tuples of columns instead. The *args
syntax lets you apply a whole sequence of rows as separate arguments:
>>> for cols in zip(*matrix): # transposed
... print ' '.join(cols)
...
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
If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:
mat = [[input() for i in range (col)] for j in range (row)]
and then enter the values you want.