在python上的matriz一侧创建条

2024-05-16 09:05:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个matriz 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|

Tags: informaindeflinepositionrangevalor
2条回答

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) + " | ")

相关问题 更多 >