在python中创建一个在1s和0s之间交替的矩阵

问题描述:

对于3 x 3矩阵,如何创建一个值在1s和0s之间交替的矩阵?

For a 3 by 3 matrix, how can I create a matrix that has values which alternate between 1s and 0s?

table = [ [ 0 for i in range(3) ] for j in range(3) ]
for row in table:
    for d1 in range(3):
        for d2 in range(3):  
            table[d1][d2]
    print row

上面是我用来创建带有零的3 x 3矩阵的代码的编辑文本,但是,我想要这样的东西

Above is edited text of the code I used to create a 3 by 3 matrix with zeros, however, I want something like this

1 0 1
0 1 0 
1 0 1

一个3 x 3矩阵,它在1和0的问题之间预先交替.有什么办法吗?

A 3 by 3 matrix that alternates between 1 and zero question beforehand. Is there any way of doing this?

您可以切片和整形.

import numpy as np
n = 3
a = np.zeros(n*n, dtype=int)
a[::2]=1
a = a.reshape(n, n)

如果您不喜欢使用numpy,则Peter Wood的建议很好且紧凑.

If you prefer not using numpy, Peter Wood's suggestion is nice and compact.