如何向矩阵添加一行零?

问题描述

在矩阵中,我们应该在索引为 K 的行之前放置一排零(不是替换 row[k-1],而是像在 row[k] 和 row[k-1] 之间放置一排零)。

名为 'change' 的函数没有按照预期的方式工作。此函数替换 row[k] 并添加额外的零行。

例如,我有 [[1,2,3],[4,5,6],[7,8,9]] 并且我想得到 [[1,[0,0],9]],所以我输入 K = 1。但是我得到的不是我想要的,而是 [[1,9]]。 bb 为矩阵,kk 为行索引。

def change(bb,kk):
    n = len(bb)
    bb.append([0]*2*n)
    n = len(bb)

    for i in range(n-1,kk-1,-1):
        bb[i] = bb[i-1]

    for j in range(0,2*n-2):
        bb[kk][j] = 0

    return bb

解决方法

你想试试这个样本吗:

import copy              # if need to make a extra new copy - deepcopy

matrix = [[1,2,3],[4,5,6],[7,8,9]]
         
kk = 1  # k must be less than the len(matrix)

def change(kk,matrix):
    new_matrix = copy.deepcopy(matrix)         # only need this,if to make a new Matrix
    
    for i,row in enumerate(matrix):
        if i == kk:
            new_matrix.insert(i,[0]*len(row))  # if need to return a new copy
            # matrix.insert(i,[0]* len(row))   # OR in-place modify & comment above line;  next line: return new_matrix
        
            
    return new_matrix                           # comment out,if in-place change
        
    
print(change(kk,matrix))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...