Iterating through a multidimensional array in Python

前端 未结 7 1499
旧巷少年郎
旧巷少年郎 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 14:12

    No one has an answer that will work form arbitrarily many dimensions without numpy, so I'll put here a recursive solution that I've used

    def iterThrough(lists):
      if not hasattr(lists[0], '__iter__'):
        for val in lists:
          yield val
      else:
        for l in lists:
          for val in iterThrough(l):
            yield val
    
    for val in iterThrough(
      [[[111,112,113],[121,122,123],[131,132,133]],
       [[211,212,213],[221,222,223],[231,232,233]],
       [[311,312,313],[321,322,323],[331,332,333]]]):
      print(val)
      # 111
      # 112
      # 113
      # 121
      # ..
    

    This doesn't have very good error checking but it works for me

提交回复
热议问题