Reputation: 1175
Given a value n
, what is the most efficient way to create a zero-indexed matrix with the column and row size equal to the value n
?
I know the following command will create a 2d matrix with 0 as all of the cell values:
[[0 for x in range(n)] for y in range(n)]
So when the n = 4
, the matrix would look as follows:
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
But is there any way to create the matrix as follows?
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]
Upvotes: 0
Views: 640
Reputation: 46901
you could simply use the current coordinates x
and y
to calculate the value x + y*n
:
n = 4
print([[x + y*n for x in range(n)] for y in range(n)])
our you could use itertools.count
:
from itertools import count
n = 4
counter = count()
print([[next(counter) for x in range(n)] for y in range(n)])
Upvotes: 1
Reputation: 13
Something like this would work.
[[i for i in range(j, j + 4)] for j in range(0, 20, 4)]
[[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]]
Upvotes: 0
Reputation: 51395
Since you are talking about 2-d matrices, and you're specifically asking about efficiency, it might be best to turn to numpy
:
import numpy as np
n = 4
my_matrix = np.arange(n*n).reshape(n,n)
>>> my_matrix
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Or you could use a list comprehension such as the following (or one of the ones suggested by @hiroprotagonist):
n = 4
my_ListOfLists = [list(range(i,i+n)) for i in range(0,n*n,n)]
>>> my_ListOfLists
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
Upvotes: 1