从矩阵输出中删除空格

Remove spaces from matrix output

我想从矩阵中删除空格:

my_list = range(10, -11, -2)  # שאלה 3 בבוחן
import numpy as np

c = np.array(my_list)
cutoff = 0
c[c < cutoff] = -1
print("new arr is:", *c,sep=' ')

import numpy as np

list_of_lists=[1,2,3],[3,2,1],[4,5,6]
matrix=np.array(list_of_lists)
print("Row 2 in matrix:",matrix[1])
import numpy as np
broad=np.full((1,3),2)
matrix=matrix*broad
    # list_of_list=matrix.tolist()
    # lst1= tr(list_of_list)
    # lst2 = lst1.replace("","").replace(",","")
    # lst3=lst2[:9]+""+lst2[9:17]+""+lst2[17:]
print("Broadcasting:",matrix)

矩阵打印为:

[[ 2  4  6]
 [ 6  4  2]
 [ 8 10 12]]

我想要

[[2  4  6]
 [6  4  2]
 [8 10 12]]

为了您的观赏乐趣,numpy 矩阵印刷精美。您可以通过将其转换为 python 列表列表并删除逗号来强制输出所需的输出:

print_me = str(list(map(list, matrix))).replace(',', '')
print(print_me)

打印:

[[2 4 6] [6 4 2] [8 10 12]]

您可以使用 repr() 函数,它 returns 字符串的可打印表示形式。

print('Broadcasting:', repr(str(matrix)).replace('\n ', '').replace('  ', ' '))

这会打印:

Broadcasting: '[[ 2 4 6][ 6 4 2][ 8 10 12]]'

没有内置选项可以删除第一个数字中的空格。但是,可以使用np.array2string将矩阵转换为字符串,然后修改字符串:

import numpy as np
import re
s = re.sub(r'\[\s*', '[', np.array2string(matrix))
print(s)

输出:

[[2  4  6]
 [6  4  2]
 [8 10 12]]