如何在嵌套的 for 循环中创建对角线?

How to create a diagonal within a nested for loop?

好的,所以我必须创建如下所示的内容:

输入板的尺寸:8

1 0 0 0 0 0 0 0

0 1 0 0 0 0 0 0

0 0 1 0 0 0 0 0

0 0 0 1 0 0 0 0

0 0 0 0 1 0 0 0

0 0 0 0 0 1 0 0

0 0 0 0 0 0 1 0

0 0 0 0 0 0 0 1

我的问题是我的代码只会创建一个 0 的矩形,我不确定如何添加 1 的对角线。

到目前为止我的代码:

dimension=int(input('Enter dimension of triangle: '))

if dimension < 2:

    print('Invalid input')

else:

    for r in range(dimension):

        for c in range(dimension):

            print("0",end=" ")

        print()

对于对角线,行索引等于列索引,所以你可以这样做:

dimension=int(input('Enter dimension of triangle: '))

if dimension < 2:
    print('Invalid input')

else:
    for r in range(dimension):
        for c in range(dimension):
            # If we are on the diagonal
            if r == c:
                num = "1"
            # Otherwise
            else:
                num = "0"

            print(num, end=" ")

        print()
>>> dimension = 8
>>> for r in range(dimension):
...     for c in range(dimension):
...          print(int(c==r), end=" ")
...     print()
... 
1 0 0 0 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 1 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 0 0 0 1 

对于一般情况,您可以像这样将备选方案放在 print 函数中

     print("1" if c==r else "0", end=" ")
a = np.zeros((8, 8), int)
np.fill_diagonal(a, 1)

然后如果你想打印它

s = StringIO()
np.savetxt(s,a,fmt="%d")
print s.getvalue()