How to convert 3D numpy array to a list of tuples?

Viewed 125

I have a 3D array of R,G,B respectively with the shape of (3,n,m), and I want to create a list of tuples that each element represents (r,g,b). I tried reshape and transpose, but it did not work as I expected

    import numpy as np 
    arr = np.array(
    [[[0, 1],
      [2, 3]],
     [[4, 5],
      [6, 7]],
     [[8, 9],
      [10,11]]]
    )

and I want to create the list like this :

[(0, 4, 8), (1, 5, 9), (2, 6, 10), (3, 7, 11)]
1 Answers

Try vstack and T with tolist:

>>> np.vstack(arr.T).tolist()
[[0, 4, 8], [2, 6, 10], [1, 5, 9], [3, 7, 11]]
>>> 

If you want tuples:

>>> list(map(tuple, np.vstack(arr.T)))
[(0, 4, 8), (2, 6, 10), (1, 5, 9), (3, 7, 11)]
>>> 
Related