如何从Python中的矩阵中删除逗号等
假设我得到了一个看起来像这样的矩阵:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
我怎样才能将它放在单独的行上:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
然后删除逗号等:
0 0 0 0 0
并且还要将其设为空白而不是0,以便稍后可以放入数字,所以最后会是像:(
_ 1 2 _ 1 _ 1
空格不下划线)
谢谢
say ive got a matrix that looks like:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
how can i make it on seperate lines:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
and then remove commas etc:
0 0 0 0 0
And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like:
_ 1 2 _ 1 _ 1
(spaces not underscores)
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这为矩阵中的每个数字分配 4 个空间。当然,您可能需要根据您的数据进行调整。
这也使用了Python 2.6中引入的字符串格式方法。询问您是否想了解如何以旧方式进行操作。
产量
This allocates 4 spaces for each number in the matrix. You may have to adjust this depending on your data of course.
This also uses the string format method introduced in Python 2.6. Ask if you'd like to see how to do it the old way.
yields
这是 ~untubu 答案的简短版本
Here is a shorter version of ~untubu's answer
这个答案还计算适当的字段长度,而不是猜测 4 :)
这里迭代太多,因此如果性能至关重要,您将需要执行初始
str()
传递和field_length
在单个非功能循环中计算。This answer also calculates the appropriate field length, instead of guessing 4 :)
There is an iteration too much here, so if performance in critical you'll want to do the initial
str()
pass andfield_length
calculation in a single non-functional loop.示例:
输出:
Example:
Output:
如果您经常使用矩阵,我强烈建议使用 numpy(第 3 方包)矩阵。它有很多与迭代相关的令人烦恼的功能(例如,标量乘法和矩阵加法)。
http://docs.scipy.org/doc/numpy/参考/生成/numpy.matrix.html
然后,如果您想让“打印”输出为您的特定格式,只需继承 numpy 的矩阵,并将 repr 和 str 方法替换为其他人提出的一些解决方案。
If you are doing a lot with matrices, I strongly suggest using numpy (3rd party package) matrix. It has a lot of features that are annoying to do with iteration (e.g., scalar multiplication and matrix addition).
http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html
Then, if you want to make "print" output your particular format, just inherit from numpy's matrix and replace the repr and str methods with some of the solutions presented by the others here.