鱼C论坛

 找回密码
 立即注册
查看: 2043|回复: 0

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

[复制链接]
发表于 2021-10-30 15:38:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

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


1.
  1. matrix = [[1, 2, 3, 4],
  2.           [5, 6, 7, 8],
  3.           [9, 10, 11, 12]]
  4.    
  5. rows = len(matrix)
  6. cols = len(matrix[0])
  7. #定义方向
  8. left = 0
  9. right = cols - 1
  10. top = 0
  11. bottom = rows - 1
  12.    
  13. result = []
  14.    
  15. while left <= right and top <= bottom:#初始条件
  16.     # 从左往右遍历
  17.     for col in range(left, right + 1):
  18.         result.append(matrix[top][col])
  19.    
  20.     # 从上往下遍历
  21.     for row in range(top + 1, bottom + 1):
  22.         result.append(matrix[row][right])
  23.    
  24.     if left < right and top < bottom:
  25.         # 从右往左遍历
  26.         for col in range(right - 1, left, -1):
  27.             result.append(matrix[bottom][col])
  28.    
  29.         # 从下往上遍历
  30.         for row in range(bottom, top, -1):
  31.             result.append(matrix[row][left])
  32.    
  33.     left = left + 1
  34.     right = right - 1
  35.     top = top + 1
  36.     bottom = bottom - 1
  37.     #循环完一次,对方位各进行一次清算,在进行下一次的循环,直到不满足初始条件而退出循环
  38. print(result)
复制代码

执行的结果如下:
  1. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
  2. >>>
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 04:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表