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

时间:2015-11-11 00:08:01

标签: python for-loop nested diagonal

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

输入董事会维度: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的矩形,我不知道如何添加1s的对角线。

到目前为止我的代码:

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()

3 个答案:

答案 0 :(得分:0)

对于对角线,行索引等于列索引,因此您可以执行:

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()

答案 1 :(得分:-1)

>>> 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=" ")

答案 2 :(得分:-1)

a = np.zeros((8, 8), int)
np.fill_diagonal(a, 1)

然后如果你想打印它

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