Iterating through a multidimensional array in Python

93,565

Solution 1

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

for cell in self.cells.flat:
    do_somethin(cell)

Solution 2

If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is!

for index,value in ndenumerate( self.cells ):
    do_something( value )
    self.cells[index] = new_value

Solution 3

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 or generator expression, but that's not very scalable or readable:

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

If you need to scale this to multiple dimensions and really want a flat list, you can write a flatten function.

Solution 4

you can get the index of each element as well as the element itself using enumerate command:

for (i,row) in enumerate(cells):
  for (j,value) in enumerate(row):
    print i,j,value

i,j contain the row and column index of the element and value is the element itself.

Solution 5

How about this:

import itertools
for cell in itertools.chain(*self.cells):
    cell.drawCell(surface, posx, posy)
Share:
93,565
utdiscant
Author by

utdiscant

Updated on October 12, 2020

Comments

  • utdiscant
    utdiscant over 3 years

    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?

  • jfs
    jfs over 14 years
    itertools.chain.from_iterable(self.cells)
  • xApple
    xApple over 12 years
    You got it wrong. It should be: for cell in [cell for row in self.cells for cell in row]: do_something(cell)
  • Shon Freelen
    Shon Freelen over 12 years
    Isn't the way he did it fine? It's just a generator expression instead of a list comprehension...am I missing something? O.o
  • tuned
    tuned about 7 years
    I think now there is a more effective way of doing this with numpy.nditer()