10

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

0

2 Answers 2

25
>>> import numpy as np
>>> np.array(data_list).reshape(-1, 2)
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

(The reshape method returns a new "view" on the array; it doesn't copy the data.)

Sign up to request clarification or add additional context in comments.

2 Comments

Numpy is a big hammer for such a problem
Numpy is in the OP's requirements.
2
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]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.