There are two lists of lists, I need to make one list out of them.
a = [[1,2,3],[4,5,6]]
b = [[1,2,3],[4,5,6]]
I_need = [[1,1,2,2,3,3],[4,4,5,5,6,6]]
or one more question, how to duplicate the list to have the same result. I will be glad for any help!
CodePudding user response:
If you have python lists:
I_need = [[e for x in zip(*l) for e in x] for l in zip(a,b)]
output: [[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6]]
If you have numpy arrays:
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2,3],[4,5,6]])
I_need = np.c_[a.ravel(), b.ravel()].reshape(2,-1)
output:
array([[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6]])
CodePudding user response:
As you marked your question with Numpy tag, I assume that you want to use just Numpy.
To easier tell apart elements of both source arrays, I defined them as:
a = [[ 1, 2, 3],[ 4, 5, 6]]
b = [[10,20,30],[40,50,60]]
To get your expected result, run:
result = np.dstack([a, b]).reshape(2, -1)
The result is:
array([[ 1, 10, 2, 20, 3, 30],
[ 4, 40, 5, 50, 6, 60]])
If you want a plain pythonic list (instead of a Numpy array), append .tolist() to your code.