如何在python中将平面列表转换为2D数组?

如何在python中将平面列表转换为2D数组?

问题描述:

我该如何打开一个列表,例如:

How can I turn a list such as:

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

插入数组(我正在使用numpy)中,如下所示:

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?

谢谢

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

( reshape 方法在数组上返回一个新的视图";它不会复制数据.)

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