Issue
I indent the print
result of numpy array with following codes.
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("a[[0,1,2]]:\n","\t",a[[0,1,2]])
But only the first row is indented, as shown in the following results :
a[[0,1,2]]:
[[1 2 3]
[4 5 6]
[7 8 9]]
And I want the output to appear as follows :
a[[0,1,2]]:
[[1 2 3]
[4 5 6]
[7 8 9]]
I could use the following code to realize the effect :
print("a[[0,1,2]]:")
count = 0
indentation = "\t "
for raw in a[[0,1,2]]:
count += 1
if count == 1:
print(indentation,"[", end = "")
print(raw)
elif count <= len(a[[0,1,2]])-1:
print(indentation,"",raw)
elif count == len(a[[0,1,2]]):
print(indentation,"",raw, end="")
print("]")
But I don't think it is a convenient way to display the outcome. Is there any way to directly move the whole array to the right in the output window?
Solution
Here is a simpler, generic, padding function:
def pad(a, sep='\t'):
from itertools import repeat
t = repeat(sep)
return '\n'.join(map(''.join, zip(t, str(a).split('\n'))))
print("a[[0,1,2]]:\n", pad(a[[0,1,2]]))
output:
a[[0,1,2]]:
[[1 2 3]
[4 5 6]
[7 8 9]]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.