在 python 上的矩阵边上创建条形

Create bars on side of a matriz on python

我想制作一个 nxn 矩阵,但我想在垂直边上放置“|”但我不能用下面的代码做到这一点:

def creatematriz(nlines, ncoluns, valor):
    M = []
    for i in range(nlines):
        line = []
        for j in range(ncoluns):
            line.append(valor)
        M.append(line)
    return M
def printMatriz(matriz):
    for line in matriz:
        for position in line:
            print(position, end=" ")
        print("|")
def main():
    m=creatematriz(20,6,'0')
    printMatriz(m)
main()

我想要这样的东西:

| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |
| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |

但我只得到:

 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|

更改您的 printMatriz 函数以在内部循环之前打印 |

def printMatriz(matriz):
    for line in matriz:
        print("|", end="")
        for position in line:
            print(position, end=" ")
        print("|")

您也可以仅使用一个循环和 join 函数:

def printMatriz(matriz):
    for line in matriz:
        print("| " + " ".join(line) + " | ")