开发者

Python Matrix, rows and columns

I have some problem matrix:

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

Ho开发者_StackOverflow社区w can from b get:

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

Many thanks


>>> 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]]]

Explanation: Consider a list:

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

You can re-create it with a list comprehension:

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

Then just wrap each element in its own list:

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

Extend that to two dimensions.


Claudiu's answer is probably more straightforward, but here is an alternative solution which recursively walks through a list of lists of any depth.

>>> 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]]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜