猿问

不使用numpy将矩阵转换为下三角

我的代码已将矩阵转换为下三角矩阵,但我需要消除一行中最后一个元素之后的空间。我的代码是


matrix = [

    [2, 9, 9],

    [5, 6, 9],

    [7, 6, 5]

]

n = len(matrix)


for i in range(n):

    for j in range(n):

        if(i<j):

            print("0",end=" ")


        else:

            print(matrix[i][j],end=" ")

    if(i!=n-1):

      print()

输出:


Expected Output    Actual Output

2 0 0\n            2 0 0 \n 

5 6 0\n            5 6 0 \n

7 6 5              7 6 5


小怪兽爱吃肉
浏览 209回答 3
3回答

慕侠2389804

用构建您想要的行的表达式替换您的内部循环。如果愿意,您可以将循环体合并为一行。for i in range(n):&nbsp; &nbsp; row = ' '.join(str(matrix[i][j]) if i >= j else "0"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for j in range(n))请注意,这消除了对最终if/print.

牛魔王的故事

n=int(input())matrix=[]for k in range(n):&nbsp; &nbsp; lst=list(map(int,input().split()))&nbsp; &nbsp; matrix.append(lst)for i in range(n):&nbsp; &nbsp; for j in range(n):&nbsp; &nbsp; &nbsp; &nbsp; if(i<j):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(j==(n-1)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("0",end='')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("0",end=" ")&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(j==(n-1)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(matrix[i][j],end='')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(matrix[i][j],end=" ")&nbsp; &nbsp; if(i!=n-1):&nbsp; &nbsp; &nbsp; print()

收到一只叮咚

n=int(input()) matrix=[] for k in range(n): lst=list(map(int,input().split())) matrix.append(lst) for i in range(n) : 对于范围内的 j (n): if(i&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; if(j==(n-1)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(matrix[i][j],end='')&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(matrix[i][j],end=" ")if(i!=n-1):&nbsp; print()
随时随地看视频慕课网APP

相关分类

Python
我要回答