Creating a list that can be used as an A x B matrix in Python is not as straightforward as creating an empty list and then trying to append or insert data to it in the place at the co-ordinates you want. You would end up getting index errors etc.
Looking at the post on matrix formation here it looks like one method is to start by appending the number of items you need for, say, each column and then taking each column and appending the number of items you need to make up the rows.
This code shows how:
# create a 2D matrix of zeros and populate itdef make_list(size):"""create a list of size number of zeros"""mylist = []for i in range(size):mylist.append(0)return mylistdef make_matrix(rows, cols):"""create a 2D matrix as a list of rows number of listswhere the lists are cols in sizeresulting matrix contains zeros"""matrix = []for i in range(rows):matrix.append(make_list(cols))return matrixmx = make_matrix(3, 3)print(mx)print('-'*34)# now populate the zero matrix# for instance put a 5 in row 0, column 0mx[0][0] = 5# put a 7 in row 1, column 1mx[1][1] = 7# put a 9 in row 2, column 2mx[2][2] = 9print(mx)
The * function helps in filling up a list with items, but if you nest it you end up then creating copies of the SAME list again. This output shows how a nested * ends up working - i.e. you try and change one part of the matrix but instead it is changed in multiple columns (strangely without an index out of range error??)
mx = [[None]*3]*3print(mx)mx[1][1] = 7print(mx)"""my output -->looks okay[[None, None, None], [None, None, None], [None, None, None]]oops!!!![[None, 7, None], [None, 7, None], [None, 7, None]]"""
However the best way seems to be to use the list function itself as shown here:
list(list(0 for i in range(3)) for j in range(3))
Remember you end up with a list of lists in Python that is referable like a basic array that you are used to.
No comments:
Post a Comment