使用理解列表创建具有交叉模式的矩阵

Using comprehension list create a matrix with cross pattern

在不使用 numpy 的情况下,我需要创建一个如下所示的矩阵:

1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1

到目前为止我只能得到这个模式:

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

使用这个理解列表:

l = [[1 if i == j else 0 for j in range(5)] for i in range(5)]

现在我需要弄清楚如何使用补偿列表将反对角线更改为相同的模式。

试试这个 -

n=7
[[1 if i==j or i+j==n-1 else 0 for j in range(n)] for i in range(n)]
[[1, 0, 0, 0, 0, 0, 1],
 [0, 1, 0, 0, 0, 1, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 0, 0, 1, 0, 0, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 1, 0, 0, 0, 1, 0],
 [1, 0, 0, 0, 0, 0, 1]]
  public static void PatternCross()
        {

            for (int row = 1; row <= n; row++)
            {
                for (int j = 0; j <= n; j++)
                {
                    if(row == j || row+j==n+1)
                    {
                        Console.Write("1");
                    }
                    else
                    {
                        Console.Write("0");

                    }

                }
               
                Console.WriteLine();
            }
        }