小蜂队 发表于 2021-10-30 15:38:32

速查Python课后第025讲:列表(VII) 逆时针输出二维列表元素思路与方法

本帖最后由 小蜂队 于 2021-12-24 20:14 编辑

0.>>> matrix = [,
...         ,
...         ]
>>> Tmatrix = [ for row in matrix] for i in range(4)]
# 这个循环的实现还是挺复杂的,开始学我就琢磨了挺久的,首先 for i in range(4) 那么 i == 0,1,2,3,
#当 i == 0,row 要取遍 matrix 中的元素的第一个值,row == matrix,matrix,matrix
#当 i == 1,row 要取遍 matrix 中的元素的第二个值,row == matrix,matrix,matrix
#以此类推
>>> Tmatrix
[, , , ]

1.matrix = [,
          ,
          ]
   
rows = len(matrix)
cols = len(matrix)
#定义方向
left = 0
right = cols - 1
top = 0
bottom = rows - 1
   
result = []
   
while left <= right and top <= bottom:#初始条件
    # 从左往右遍历
    for col in range(left, right + 1):
      result.append(matrix)
   
    # 从上往下遍历
    for row in range(top + 1, bottom + 1):
      result.append(matrix)
   
    if left < right and top < bottom:
      # 从右往左遍历
      for col in range(right - 1, left, -1):
            result.append(matrix)
   
      # 从下往上遍历
      for row in range(bottom, top, -1):
            result.append(matrix)
   
    left = left + 1
    right = right - 1
    top = top + 1
    bottom = bottom - 1
    #循环完一次,对方位各进行一次清算,在进行下一次的循环,直到不满足初始条件而退出循环
print(result)
执行的结果如下:
>>>
页: [1]
查看完整版本: 速查Python课后第025讲:列表(VII) 逆时针输出二维列表元素思路与方法