How to print rows of identity matrix

Viewed 76

Essentially what I want to print is something like this:

(1 0 0 0), (0 1 0 0), (0 0 1 0), (0 0 0 1)

I tried the following code to see if I could work out a solution but without much success.

zeros = [0, 0, 0, 0]

for x in zeros:
   print(x + 1)

And at that point I couldn't think of any way to only change one of the zeros to a one or to change them all to a one and then somehow revert them back to zeros.

7 Answers
zeros = [0, 0, 0, 0]

for i in range(len(zeros)):
    zeros=[0,0,0,0]
    zeros[i]=1
    print(zeros)
zeros = [0, 0, 0, 0]
outp=[]

for key, val in enumerate(zeros):
    temp = zeros.copy()
    temp[key] = 1
    outp.append(tuple(temp))

print(outp)

Output:

[(1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)]
zeros = [0, 0, 0, 0]

for i,x in enumerate(zeros):
  zeros[i]= 1
  print(zeros)
  zeros[i] = 0

Output:

[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
In [94]: for i in range(len(zeros)): 
    ...:     zeros[i] = 1 
    ...:     print(tuple(zeros)) 
    ...:     zeros[i] = 0 
    ...:                                                                                                                                      
(1, 0, 0, 0)
(0, 1, 0, 0)
(0, 0, 1, 0)
(0, 0, 0, 1)
zeros = [0, 0, 0, 0]
zerolen = len(zeros)

for x in range(0, zerolen):
    zerostr = f"{'0' * x}1{'0' * (zerolen - (x + 1))}"
    print(zerostr)
for i in range(len(zeros)):
    tmp = zeros.copy()
    tmp[i] += 1
    print(tmp)

As simple as:

for x in np.eye(4):
   print(tuple(x))

output:

(1.0, 0.0, 0.0, 0.0)
(0.0, 1.0, 0.0, 0.0)
(0.0, 0.0, 1.0, 0.0)
(0.0, 0.0, 0.0, 1.0)

if you want to print them in the same line, use end:

for x in np.eye(4):
    print(tuple(x), end=' ')

output:

(1.0, 0.0, 0.0, 0.0) (0.0, 1.0, 0.0, 0.0) (0.0, 0.0, 1.0, 0.0) (0.0, 0.0, 0.0, 1.0) 
Related