开发者社区> 问答> 正文

没有包的Python中的顺序整数矩阵

就在我觉得自己很正派的时候,我发现一件简单的事情我无法克服。

我需要创建一个对称的行x列矩阵,其中指定了校验和的开始和块。条目应按顺序排列。

def main(start_index, block):
    num_rows, num_cols = block, block
    matrix = []

    for r in range(num_rows):
        temp = []

        for c in range(num_cols):
            temp.append(c)

        matrix.append(temp)

    return matrix

输出是: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

我想要获得的是: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

不仅是3x3,而且是动态的。

注意:没有像numpy这样的软件包,这不是要问的重点。仅本机python。

展开
收起
几许相思几点泪 2019-12-29 19:01:32 735 0
1 条回答
写回答
取消 提交回答
  • 您要追加的c值始终在0到之间num_cols。您需要c根据您所在的行进行计算。类似:

    def main(start_index, block):
        num_rows, num_cols = block, block
        matrix = []
    
        for r in range(num_rows):
            temp = []
    
            for c in range(0, num_cols):
                temp.append(start_index + c + (r * num_cols))
    
            matrix.append(temp)
    
        return matrix
    
    main(0, 3)
    
    >> [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    
    

    您也可以将此作为生成器从start_index写入row * columns,从而懒惰地生成行。例如:

    def main(start_index, block):
        num_rows, num_cols = block, block
    
        total = num_rows * num_cols
    
        for i in range(start_index, total + start_index, num_cols):
            yield list(range(i, num_cols + i))
    
    list(main(10, 4))
    >> [[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21], [22, 23, 24, 25]]
    
    2019-12-29 19:02:05
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载