Iterating through a multidimensional array in Python

前端 未结 7 1500
旧巷少年郎
旧巷少年郎 2020-12-13 13:35

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

7条回答
  •  一向
    一向 (楼主)
    2020-12-13 13:57

    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.

提交回复
热议问题