从1D列表中创建2D列表

Pho*_*One 12 python matrix

我有点新的Python,我想一维列表转换为二维表,考虑到widthlengthmatrix.

说我有一个list=[0,1,2,3],我想制作2 by 2这个列表的矩阵.

我怎样才能得到matrix [[0,1],[2,3]] width= 2,length= 2 list

roo*_*oot 26

尝试类似的东西:

In [53]: l = [0,1,2,3]

In [54]: def to_matrix(l, n):
    ...:     return [l[i:i+n] for i in xrange(0, len(l), n)]

In [55]: to_matrix(l,2)
Out[55]: [[0, 1], [2, 3]]
Run Code Online (Sandbox Code Playgroud)

  • 在 python 3 中,“xrange”被重命名为“range” (3认同)

wim*_*wim 7

我认为你应该使用numpy,它是专门用于处理矩阵/数组而不是列表列表.这看起来像这样:

>>> import numpy as np
>>> list_ = [0,1,2,3]
>>> a = np.array(list_).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.shape
(2, 2)
Run Code Online (Sandbox Code Playgroud)

避免调用变量,list因为它会影响内置名称.

  • 这取决于你需要2D结构的东西,但是当你以几乎任何方式使用矩阵时,numpy将更加高效,方便和灵活. (3认同)