views:

1752

answers:

4

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?

+1  A: 

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.

Eevee
+12  A: 

It's clear you're using numpy. With numpy you can just do:

for cell in self.cells.flat:
    do_somethin(cell)
tom10
+2  A: 

How about this:

import itertools
for cell in itertools.chain(*self.cells):
    cell.drawCell(surface, posx, posy)
Tim Pietzcker
`itertools.chain.from_iterable(self.cells)`
J.F. Sebastian
A: 

for cell in [cell for cell in row for row in self.cells]: do_something(cell)

I dont have this working.. Looking for a solution using list comprehension.