我有点新的Python,我想一维列表转换为二维表,考虑到width与length此matrix.
说我有一个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)
我认为你应该使用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因为它会影响内置名称.
| 归档时间: |
|
| 查看次数: |
22277 次 |
| 最近记录: |