在python中创建一个在1s和0s之间交替的矩阵 [英] Creating a matrix in python alternating between 1s and 0s

查看:442
本文介绍了在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.

这篇关于在python中创建一个在1s和0s之间交替的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆