One solution is to use a numpy (download here) matrix
:
>>> from numpy import zeros, matrix
>>> n = 2
>>> mat = matrix(zeros([3*n, 7]))
>>> mat
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., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
However, as noted above by @joris, with a numpy matrix all of your data must be of the same type.
>>> mat[0,2] = 14
>>> mat
matrix([[ 0., 0., 14., 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.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
>>> mat[0,1] = 's'
Traceback (most recent call last):
File "<pyshell#139>", line 1, in <module>
mat[0,1] = 's'
ValueError: could not convert string to float: s
You probably want to use a nested list
instead, since this is by far a more flexible and generic data type, and in addition is easier to get the hang of. For that I would refer you to this question, since @Mike Graham does a right proper job of explaining them. You might want to define a method like:
def shape_zeros(n):
# Here's where you build up your "matrix"-style nested list
pass # The pass statement does nothing!
Here are a couple of hints for filling up the code body of the above function. First, you can construct a whole list of duplicates with the *
asterisk operator:
>>> row = [0] * 7
>>> row
[0, 0, 0, 0, 0, 0, 0]
Next, you can nest lists within lists; but be careful when moving lists around, as the list's name is actually like a pointer:
>>> mat = []
>>> n = 2
>>> for i in range(n*3):
mat.append(row)
>>> mat
[[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, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
>>> mat[0][0] = 1
>>> mat
[[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0]]
You can avoid the above problem by creating your sub-lists (rows) separately or using a list(old_list)
constructor function to make a copy. When you build it right, you can access/manipulate an element of a nested list like this:
>>> mat[0][0] = 1
>>> mat[1][2] = 'Q_Q'
>>> mat[2][0] = 3
>>> mat[2][2] = 5
>>> mat
[[1, 0, 0, 0, 0, 0, 0],
[0, 0, 'Q_Q', 0, 0, 0, 0],
[3, 0, 5, 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]]
Good luck!