I have created a multidimensional array in Python like this:
self.cells = np.empty((r,c),dtype=np.object)
Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?
I have created a multidimensional array in Python like this:
self.cells = np.empty((r,c),dtype=np.object)
Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?
Just iterate over one dimension, then the other.
for row in self.cells:
for cell in row:
do_something(cell)
Of course, with only two dimensions, you can compress this down to a single loop using a list comprehension, but that's not very scalable or readable:
for cell in [cell for cell in row for row in self.cells]:
do_something(cell)
If you need to scale this to multiple dimensions and really want a flat list, you can write a flatten
function.
It's clear you're using numpy. With numpy you can just do:
for cell in self.cells.flat:
do_somethin(cell)
How about this:
import itertools
for cell in itertools.chain(*self.cells):
cell.drawCell(surface, posx, posy)