Need to make a 6x8 matrix. In this matrix, need to assign values to various cells within the matrix and then simulate a heating/cooling system. Before I get there though, I need to make sure this is right. Is this how you make rows and columns? Does it matter that it does not display this way when printed? Like I said I need to assign values to each of theses cells, does it matter that some already have a value by the way I made the lists? Is there a way to make the list without any initial values?
matrix = [] # Create an empty list
numberOfRows = 6
numberOfColumns = 8
for row in range(0, numberOfRows):
matrix.append([]) # Add an empty new row
for column in range(0, numberOfColumns):
matrix[row].append(column)
print(matrix)
[[0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7]]
Yes, it is a good method. However, it is much easier and more pythonic to use list comprehension : matrix = [list(range(numberOfColumns)) for _ in range(numberOfRows)]
And yes, you can make a list with no value : []
or list()
And even a 2-dimensional list : [[]]
However, it has no use.
You can use this way to make 2D arrays, but a few comments:
matrix[row].append(0)
. This is mostly a design choice. For example, if, in your program, later on you do not change the values at every position, then you will be left with old values from the initialization. range(0, numberOfRows)
to range(numberOfRows)
; it starts from 0 by default.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.