如何从Python中的矩阵中删除逗号等

发布于 2024-09-03 03:39:19 字数 369 浏览 3 评论 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

并且还要将其设为空白而不是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 技术交流群。

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

发布评论

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

评论(6

顾铮苏瑾 2024-09-10 03:39:19

这为矩阵中的每个数字分配 4 个空间。当然,您可能需要根据您的数据进行调整。

这也使用了Python 2.6中引入的字符串格式方法。询问您是否想了解如何以旧方式进行操作。

matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in matrix:
    data=(str(num) if num else ' ' for num in row])   # This changes 0 to a space
    print(' '.join(['{0:4}'.format(elt) for elt in data]))

产量

     1    2             
     1                  
20                  1   

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.

matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in matrix:
    data=(str(num) if num else ' ' for num in row])   # This changes 0 to a space
    print(' '.join(['{0:4}'.format(elt) for elt in data]))

yields

     1    2             
     1                  
20                  1   
横笛休吹塞上声 2024-09-10 03:39:19

这是 ~untubu 答案的简短版本

M = [[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in M:
    print " ".join('{0:4}'.format(i or " ") for i in row)

Here is a shorter version of ~untubu's answer

M = [[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]
for row in M:
    print " ".join('{0:4}'.format(i or " ") for i in row)
℉絮湮 2024-09-10 03:39:19
#!/usr/bin/env python

m = [[80, 0, 3, 20, 2], [0, 2, 101, 0, 6], [0, 72 ,0, 0, 20]]

def prettify(m):
    for r in m:
        print ' '.join(map(lambda e: '%4s' % e, r)).replace(" 0 ", "   ")

prettify(m)

# => prints ...
# 80         3   20    2
#       2  101         6
#      72             20
#!/usr/bin/env python

m = [[80, 0, 3, 20, 2], [0, 2, 101, 0, 6], [0, 72 ,0, 0, 20]]

def prettify(m):
    for r in m:
        print ' '.join(map(lambda e: '%4s' % e, r)).replace(" 0 ", "   ")

prettify(m)

# => prints ...
# 80         3   20    2
#       2  101         6
#      72             20
月朦胧 2024-09-10 03:39:19

这个答案还计算适当的字段长度,而不是猜测 4 :)

def pretty_print(matrix):
  matrix = [[str(x) if x else "" for x in row] for row in matrix]
  field_length = max(len(x) for row in matrix for x in row)
  return "\n".join(" ".join("%%%ds" % field_length % x for x in row)
                   for row in matrix)

这里迭代太多,因此如果性能至关重要,您将需要执行初始 str() 传递和 field_length 在单个非功能循环中计算。

>>> matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 1, 1, 1, 0.30314]]
>>> print pretty_print(matrix)
              1       2                
              1                        
     20       1       1       1 0.30314
>>> matrix=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> print pretty_print(matrix)
1    
  1  
    1

This answer also calculates the appropriate field length, instead of guessing 4 :)

def pretty_print(matrix):
  matrix = [[str(x) if x else "" for x in row] for row in matrix]
  field_length = max(len(x) for row in matrix for x in row)
  return "\n".join(" ".join("%%%ds" % field_length % x for x in row)
                   for row in matrix)

There is an iteration too much here, so if performance in critical you'll want to do the initial str() pass and field_length calculation in a single non-functional loop.

>>> matrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 1, 1, 1, 0.30314]]
>>> print pretty_print(matrix)
              1       2                
              1                        
     20       1       1       1 0.30314
>>> matrix=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> print pretty_print(matrix)
1    
  1  
    1
甜`诱少女 2024-09-10 03:39:19
def matrix_to_string(matrix, col):
        lines = []
        for e in matrix:
            lines.append(str(["{0:>{1}}".format(str(x), col) for x in e])[1:-1].replace(',','').replace('\'',''))
        pattern = re.compile(r'\b0\b')
        lines = [re.sub(pattern, ' ', e) for e in lines]
        return '\n'.join(lines)

示例:

matrix = [[0,1,0,3],[1,2,3,4],[10,20,30,40]]
print(matrix_to_string(matrix, 2))

输出:

    1     3
 1  2  3  4
10 20 30 40
def matrix_to_string(matrix, col):
        lines = []
        for e in matrix:
            lines.append(str(["{0:>{1}}".format(str(x), col) for x in e])[1:-1].replace(',','').replace('\'',''))
        pattern = re.compile(r'\b0\b')
        lines = [re.sub(pattern, ' ', e) for e in lines]
        return '\n'.join(lines)

Example:

matrix = [[0,1,0,3],[1,2,3,4],[10,20,30,40]]
print(matrix_to_string(matrix, 2))

Output:

    1     3
 1  2  3  4
10 20 30 40
很糊涂小朋友 2024-09-10 03:39:19

如果您经常使用矩阵,我强烈建议使用 numpy(第 3 方包)矩阵。它有很多与迭代相关的令人烦恼的功能(例如,标量乘法和矩阵加法)。

http://docs.scipy.org/doc/numpy/参考/生成/numpy.matrix.html

然后,如果您想让“打印”输出为您的特定格式,只需继承 numpy 的矩阵,并将 repr 和 str 方法替换为其他人提出的一些解决方案。

class MyMatrix(numpy.matrix):
   def __repr__(self):
      repr = numpy.matrix.__repr__(self)

      ...

      return pretty_repr

   __str__ = __repr__

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.

class MyMatrix(numpy.matrix):
   def __repr__(self):
      repr = numpy.matrix.__repr__(self)

      ...

      return pretty_repr

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