Python矩阵,行和列

时间:2011-05-10 19:39:37

标签: python matrix

我有一些问题矩阵:

b=   [[-2.5,  0.5],        #b is random matrix
     [-1.5, -0.5],
     [-0.5,  0.5]]

如何从b获得:

b=[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]

非常感谢

2 个答案:

答案 0 :(得分:4)

>>> b=   [[-2.5,  0.5],        #b is random matrix
     [-1.5, -0.5],
     [-0.5,  0.5]]
>>> [[[val] for val in row] for row in b]
[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]

说明:考虑一个清单:

>>> oned = [1, 2, 3]

您可以使用列表解析重新创建它:

>>> [val for val in oned] 
[1, 2, 3]

然后将每个元素包装在自己的列表中:

>>> [[val] for val in oned]
[[1], [2], [3]]

将其扩展到两个维度。

答案 1 :(得分:1)

Claudiu's answer可能更直接,但这里有一个替代解决方案,递归遍历任何深度的列表列表。

>>> listify = lambda x: map(listify, x) if isinstance(x, list) else [x]
>>> listify(b)
[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]