简体   繁体   中英

Creating a matrix in python alternating between 1s and 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

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.

values is an iterator that yields 0 and 1 forever:

>>> from itertools import cycle
>>> values = cycle([0, 1])
>>> [[next(values) for i in range(3)] for j in range(3)]
[[0, 1, 0],
 [1, 0, 1],
 [0, 1, 0]]

It works well when the number of columns is odd, not when it's even:

>>> values = cycle([0, 1])
>>> [[next(values) for i in range(5)] for j in range(4)]
[[0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1]]

>>> values = cycle([0, 1])
>>> [[next(values) for i in range(4)] for j in range(5)]
[[0, 1, 0, 1],
 [0, 1, 0, 1],
 [0, 1, 0, 1],
 [0, 1, 0, 1],
 [0, 1, 0, 1]]

If you want to avoid using numpy :

flat_list = [1-i%2 for i in xrange(9)]
print [flat_list[i:i+3] for i in xrange(0,9,3)]

Here is a function to create a nxm 1 0 matrix. If you want to start with 0 1 sequence, consider to modify the code block a litte.

import numpy as np
def my_one_zero_matrix(n,m):
    zeros_a=np.zeros((n,m))
    for i in range(n):
        for j in range(m):
            if (i+j)%2==0:
                zeros_a[i,j]=1
    return zeros_a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM