Home > Blockchain >  Remove spaces from matrix output
Remove spaces from matrix output

Time:12-12

I want to remove spaces from the matrix:

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)

The matrix print is:

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

And I want

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

CodePudding user response:

The numpy matrix is pretty-printed for your viewing pleasure. You can force your desired output by converting it to a python list-of-lists and deleting the commas:

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

which prints:

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

CodePudding user response:

You can use the repr() function which returns the printable representation of the string.

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

This prints:

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

CodePudding user response:

There is no built-in option to remove the spaces from the first numbers. However, you can use np.array2string to convert the matrix to a string and then modify the string:

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

Output:

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