欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法优化:转置矩阵和转置方阵打印

程序员文章站 2024-03-22 11:46:34
...

转置方阵:

lst = [1,2,3,4,5,6,7,8,9]
width = 3

for i in range(0,len(lst),width):
    print(lst[i:i+3])

print('----------------')

width = 3
lines = len(lst)//width

for i in range(lines):
    print(lst[i::3])

运行结果:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
----------------
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

转置矩阵:

lst = [1,2,3,4,5,6]
width = 3
lines = int(len(lst)/width)
i = 0

for _ in range(lines):
    print(lst[i:i+3])
    i = i+3

print('----------')

width = 2
lines = int(len(lst)/width)

for i in range(lines):
    print(lst[i::3])

运行结果:

[1, 2, 3]
[4, 5, 6]
----------
[1, 4]
[2, 5]
[3, 6]