xplodnow xplodnow - 1 month ago 7
Python Question

Merge two arrays into an list of arrays

Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.

Essentially what I have in a simplified form:

dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]

x = []
for i in range(3):
x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0)


what it gives:

x = [1,2,3,4,5,6,7,8]


what I want:

x = [[1,2,3],[4,5,6],[6,7]]


I want to use the for loop because I have too many arrays to 'compile' and cant key in them one by one would be very inefficient. This way I can use the created array to plot a boxplot directly.

A simiiliar question exists with no loop requirement but still does not have proper solution. Link

Answer

Comprehension:

# using name as "dict" is not proper use "_dict" otherwise.
dict['w1']=[1,2,3]
dict['w2']=[4,5,6]
dict['w3']=[7,8]

x = [dict["w"+str(i)] for i in range(1, 4)]

gives output:

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