簡體   English   中英

如何從python中的矩陣中刪除逗號等

[英]How to remove commas etc from a matrix in 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

(空格不是下划線)

謝謝

這將為矩陣中的每個數字分配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   

這是〜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)
#!/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

這個答案還計算了適當的字段長度,而不是猜測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
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

如果您要處理大量矩陣,我強烈建議您使用numpy(第三方軟件包)矩陣。 它具有許多煩人的與迭代有關的功能(例如,標量乘法和矩陣加法)。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html

然后,如果要“打印”輸出您的特定格式,只需繼承numpy的矩陣,並用此處其他解決方案提供的一些解決方案替換repr和str方法。

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

      ...

      return pretty_repr

   __str__ = __repr__

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM