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

时间:2022-10-17 21:30:45

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:

到一个数组(我使用numpy)看起来像:

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

1 个解决方案

#1


18  

>>> 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.)

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

#1


18  

>>> 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.)

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