Reputation: 3
I have the following code:
matrix = [[0, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 1]]
I am able to print every line as follows using this:
for i in matrix:
print(*i)
outputting:
0 0 1 0
1 1 0 0
0 0 0 1
1 0 0 1
I want to create custom boundaries for each line and I am able to do so with by manually adding the boundaries to the list of list as shown below:
for k in range(0,columns):
matrix[k].insert(0,'[')
matrix[k].insert(columns+1,']')
giving me the output as desired:
[ 0 0 1 0 ]
[ 1 1 0 0 ]
[ 0 0 0 1 ]
[ 1 0 0 1 ]
Is there a better way to do this, particularly without having to add the boundaries into my list?
Upvotes: 0
Views: 67
Reputation: 38502
Another way with simple list
to str
casting and replacing all the commas with nothing like below-
matrix = [[0, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 1]]
for i in matrix:
print(str(i).replace(',',''))
DEMO: https://rextester.com/QESAJC13339
Upvotes: 0
Reputation: 51998
for row in matrix:
print(row)
almost does what you want, but it has commas. Replace those commas by nothing:
for row in matrix:
print(str(row).replace(',',''))
[0 0 1 0]
[1 1 0 0]
[0 0 0 1]
[1 0 0 1]
Even this isn't quite what your target is, but in mathematical type-setting it is not customary to pad the boundaries of a matrix with white space.
Upvotes: 0
Reputation: 392
Yes you can do it with two for loop like that
for i in matrix:
s = "["
for j in i:
s = s + str(j) + " "
s = s + "]"
print(s)
Or you can still do it with 1 for loop like that
for i in matrix:
print("[", *i, "]")
Upvotes: 1