Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Stack elements from a 3D list in Python

I have two lists like these:

x = np.array([1,2,3,4,5])

y_all = [[2,3,5,4,6], 

         [3,2,4,3,5], 

         [4,5,4,3,4]]

And I need the output to be like this:

[(1, 2),
(2, 3),
(3, 5),
(4, 4),
(5, 6),
(1, 3),
(2, 2),
(4, 3),
(5, 5),
(1, 4),
(2, 5),
(3, 4),
(4, 3),
(5, 4),]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do this more efficiently so that if I have a larger size of x and y_all I can do that?

This is what I have tried so far:

import numpy as np

y=np.array(y_all).T

y_all_fin = []

for i in range(len(y[0])):

    inter = np.vstack((x,y_all[i]))
    y_all_fin.append(inter)

points = np.hstack((y_all_fin[0],y_all_fin[1],y_all_fin[2])).T

N = []

for i in range(len(points[:,0])):

    new = tuple(points[i])

    N.append(new)

>Solution :

You can do it with this simple 1-liner:

[a for y in y_all for a in zip(x,y)]

Note that there is little point using numpy if your arrays contain object (non numerical) types like tuples…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading