Are there ways to form a list from two arrays without using for loop?

I have two arrays, say Y and X, both of them are three dimensional array, say 2X3X4. I want to construct a list like [(X[0][0][0],Y[0][0][0]),(X[0][0][1],Y[0][0][1]),...,X[1][2][3],Y[1][2][3]]. Are there any methods to do it in python without using for loop?

Answer

You may first flatten your arrays, into a one-dimensionnal array

import numpy as np
a = np.random.rand(2, 3, 4) # shape is [2, 3, 4]
a = a.reshape([1, 24])      # shape is [1, 24] so flattened

b = np.random.rand(2, 3, 4)
b = b.reshape([1, 24])

Then zip them to pair them

r = list(zip(a[0], b[0]))
print(r) # [(10, 1), (20, 2), (30, 3), (40, 4), (50, 5), (60, 6), (100, 10), (110, 11), (120, 12), (130, 13), (140, 14), (150, 15)]

Leave a Reply

Your email address will not be published. Required fields are marked *