算法优化:转置矩阵和转置方阵打印
程序员文章站
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]