Home > Blockchain >  How can I make a new list that has the first element of each of the list but split into 3?
How can I make a new list that has the first element of each of the list but split into 3?

Time:10-10

If I start off with this

A = [[1,3,5,7,2,2], [2,3,1,2,1,1]]
B = [[3,2,5,5,6,6], [2,1,4,2,7,2]]
C = [[1,0,2,4,8,2], [9,7,2,2,7,2]]

How can I achieve this output?

[[1,3],[5,7],[2,2],[3,2],[5,5],[6,6],[1,0],[2,4],[8,2]] 

CodePudding user response:

numpy buffs won't like it, but you can extract the first elements as regular python lists and join them (first_elems below), and then take pair elements from this list and convert back to a numpy array.

from numpy import array
A = array([[1,3,5,7,2,2], [2,3,1,2,1,1]])
B = array([[3,2,5,5,6,6], [2,1,4,2,7,2]])
C = array([[1,0,2,4,8,2], [9,7,2,2,7,2]])

first_elems = list(A[0])   list(B[0])   list(C[0])
array(list(zip(first_elems[::2], first_elems[1::2])))

CodePudding user response:

If it's list, you can do a nested for loops:

result = []
for list_ in [A,B,C]:
    for i in range(int(len(list_[0])/2)):
        result.append(list_[0][i*2:i*2 2])

[[1, 3], [5, 7], [2, 2], [3, 2], [5, 5], [6, 6], [1, 0], [2, 4], [8, 2]]

Or a list comprehension

[list_[0][i*2:i*2 2] for list_ in [A,B,C] for i in range(int(len(list_[0])/2))]

If it's numpy array, you can use concatenate and reshape

concat_array = np.concatenate((A[0],B[0],C[0]))

concat_array.reshape(9,2)

array([[1, 3],
       [5, 7],
       [2, 2],
       [3, 2],
       [5, 5],
       [6, 6],
       [1, 0],
       [2, 4],
       [8, 2]])
  • Related