我找到了这个练习来研究 Python 中的矩阵或 2d 向量(我是初学者)
'''
start row index - k
end row index - m
start column index - l
end column index - n
iterator - i
array or list - a
'''
# Python3 program to print
# given matrix in spiral form
def spiralPrint(m, n, a) :
k = 0; l = 0
''' k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator '''
while (k < m and l < n) :
# Print the first row from
# the remaining rows
for i in range(l, n) :
print(a[k][i], end = " ")
k += 1
# Print the last column from
# the remaining columns
for i in range(k, m) :
print(a[i][n - 1], end = " ")
n -= 1
# Print the last row from
# the remaining rows
if ( k < m) :
for i in range(n - 1, (l - 1), -1) :
print(a[m - 1][i], end = " ")
m -= 1
# Print the first column from
# the remaining columns
if (l < n) :
for i in range(m - 1, k - 1, -1) :
print(a[i][l], end = " ")
l += 1
a =[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]]
R = 4
C = 5
spiralPrint(R,C,a)
我想了解它背后的逻辑,我的意思是为什么使用 4 个循环进行迭代以及为什么将索引分配为行和列?此外,该函数如何准确地知道在元素的末尾它必须进入第二个列表并四处走动?