Reputation: 3397
I have one loop nested inside another one:
position={}
n=2
for i in range(n):
i=str(i)
for j in range(n):
j=str(j)
position[str(i+j)]= #whatever (in my case an object)
This way the key values of the dictionary are the indices from the matrix and I just need to call with position['11']
to get it.
Is there a better way to join i
and j
? And store (and create) a matrix-like data?
PS: I know about the numpy
library but I haven't succeed to install it yet... but that is another question...
Upvotes: 0
Views: 2413
Reputation: 35580
The "right" answer is to figure out how to install Numpy, since that will improve your programming toolset much more than writing a homegrown pseudo-matrix class.
However, if you want to do it your way, this is going to cause problems:
position[str(i+j)]
How will you tell the difference between 2,11
and 21,1
.?
So your dict key will need to be something like
position["{},{}".format(i,j)]
Or as @user2.3M suggests:
position[(i,j)]
But you don't really want to be building complex strings or new tuples for each "matrix" access.
Unless the map is very large and sparse, you are much better off using one of the list-based versions in @JAB's answer.
Upvotes: 1
Reputation: 281633
Your dictionary is a headache waiting to happen. It can't distinguish between row 1, column 11 and row 11, column 1.
If you can't get NumPy working, the standard solution to your problem is a nested list:
matrix = [[whatever() for i in xrange(n)] for j in xrange(n)]
You would index this with matrix[i][j]
.
You could also use a dict indexed with tuples:
matrix = {(i, j): whatever() for i in xrange(n) for j in xrange(n)}
and index it with matrix[i, j]
. This may surprise people who need to maintain your code.
Upvotes: 2
Reputation: 21089
If you don't want to use numpy
, you could use nested lists (equivalent to multidimensional arrays in C):
position=[]
n=2
for i in range(n):
position.append([])
for j in range(n):
position[i].append(some_object)
And then you reference it using position[i][j]
.
An alternative method would be to use a flat list and index into it using calculated values (basically what happens when you index into a 2D array in C and the like, as those are stored as one contiguous array and the compiler performs some math on the multiple indices you supply to index into that underlying flat array):
position=[]
n, m = 2, 3
for i in range(n):
for j in range(m):
position.append(some_object)
# do something with the object at (i, j)
position[m*i + j].do_something() # there are m elements between (i, j) and (i+1, j)
Upvotes: 1