Reshape 1D List to 2D List -Python


I have the following list:

a = ['2', '3', '4', '7', '5']

I want to transform to a 2D matrix knowing that I have 4 columns, I do not consider rows here

I want to achieve this without repeating the items, just fill the rest with None or empty space as follows:

New_a = [['2', '3', '4', '7'],
         ['5', None, None, None]] 

I tried to reshape it using reshape function, but it did not work, because the target matrix is not consistent.

I also tried (resize function). It did not work because it repeat the items once there are some gaps at the end.

Asked By: jamal manssour



New_a = []
a = ['2', '3', '4', '7', '5']
for i in range(0,len(a),4) :
if len(New_a[-1]) != 4 :
    New_a[-1] += [None]*(4-len(New_a[-1])) 

output :-

[['2', '3', '4', '7'], ['5', None, None, None]]

This should work for different lengths of the 1d array a

You can also use reisze() function of numpy array but it will fill your array with empty strings instead of None.

Example :-

a = ['2', '3', '4', '7', '5']

a1 will look like this:-

array([['2', '3', '4', '7'],
       ['5', '', '', '']], dtype='<U1')
Answered By: Nehal Birla
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.