Skip to content
Advertisement

how to convert 1d list to 2d list with some some number of columns?

I want to convert a 1d list to 2d in python. I found a way to do it with NumPy, but it gives the following error when the length of the list is not divisible by the number of columns:

ValueError: cannot reshape array of size 9 into shape (4)

In the case that the length is not divisible, I want to add none to fill the spaces. Like so:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = some_func(a)
print(b)

and the output should be:

[[1, 2, 3, 4], 
[5, 6, 7, 8], 
[9, None, None, None]] 

Please help me. My current code is:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = numpy.reshape(a, (-1, 4))
print(a)

Advertisement

Answer

This should work.

from math import ceil

def my_reshape(arr, cols):
    rows = ceil(len(arr) / cols)
    res = []
    for row in range(rows):
        current_row = []
        for col in range(cols):
            arr_idx = row * cols + col
            if arr_idx < len(arr):
                current_row.append(arr[arr_idx])
            else:
                current_row.append(None)
        res.append(current_row)
    return res
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement