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
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
A 3 by 3 matrix that alternates between 1 and zero question beforehand. Is there any way of doing this?
解决方案
You could slice and reshape.
import numpy as np
n = 3
a = np.zeros(n*n, dtype=int)
a[::2]=1
a = a.reshape(n, n)
If you prefer not using numpy, Peter Wood's suggestion is nice and compact.