Python 矩阵、行和列

发布于 2024-11-06 06:44:55 字数 239 浏览 3 评论 0原文

我有一些问题矩阵:

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

非常感谢

I have some problem matrix:

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

How can from b get:

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

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一直在等你来 2024-11-13 06:44:55
>>> 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]]

将其扩展到二维。

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

摇划花蜜的午后 2024-11-13 06:44:55

克劳迪乌的答案可能更简单,但这里有一个替代解决方案递归地遍历任意深度的列表的列表。

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

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]]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文