Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn a flat list into a 2D array in python?

How can I turn a list such as:

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

into a array (I'm using numpy) that looks like:

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

Can I slice segments off the beginning of the list and append them to an empty array?

Thanks

like image 544
Double AA Avatar asked Jul 07 '11 16:07

Double AA


1 Answers

def nest_list(list1,rows, columns):    
        result=[]               
        start = 0
        end = columns
        for i in range(rows): 
            result.append(list1[start:end])
            start +=columns
            end += columns
        return result

for:

 list1=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
nest_list(list1,4,4)

Output:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
like image 53
Amgad Avatar answered Oct 05 '22 09:10

Amgad