Python 二维Cell数组遍历顺序调整:从固定X遍历Y改为固定Y遍历X
魔方格子遍历顺序问题
问题描述
我有一个由Cell对象组成的二维数组,需要按照类似阅读书籍的顺序遍历单元格,但当前的遍历逻辑是固定X坐标先遍历所有Y坐标,不符合需求。
当前实际遍历顺序
- (X: 3 Y: 0)
- (X: 3 Y: 1)
- (X: 3 Y: 2)
- (X: 4 Y: 0)
- (X: 4 Y: 1)
- (X: 4 Y: 2)
- (X: 5 Y: 0)
- (X: 5 Y: 1)
- (X: 5 Y: 2)
期望遍历顺序
先按Y坐标从小到大排序,同一Y值下再按X坐标从小到大遍历,类似书本逐行阅读,示例顺序为:
- (X: 3 Y: 0)
- (X: 4 Y: 0)
- (X: 5 Y: 0)
- (X: 3 Y: 1)
- (X: 4 Y: 1)
- ...以此类推(注:原描述此处笔误写为(X:4 Y:2),已修正为符合逻辑的顺序)
现有代码
U, L, F, R, B, D = ('U', 'L', 'F', 'R', 'B', 'D') class Cell: def __init__(self, row, col, width, total_rows): self.row = row self.col = col self.x = row * width self.y = col * width self.color = WHITE self.width = width self.total_rows = total_rows def get_cords(self): return self.row, self.col # 生成网格 def make_grid(rows, width): grid = [] gap = width // rows for i in range(rows): grid.append([]) for j in range(rows): cell = Cell(i, j, gap, rows) grid[i].append(cell) return grid def get_side(cell): x, y = cell.get_cords() if x >= 3 and x <= 5 and y >= 3 and y <= 5: return F if x >= 3 and x <= 5 and y >= 0 and y <= 3: return U if x >= 3 and x <= 5 and y >= 6 and y <= 8: return D if x >= 0 and x <= 2 and y >= 3 and y <= 5: return L if x >= 6 and x <= 8 and y >= 3 and y <= 5: return R if x >= 9 and x <= 11 and y >= 3 and y <= 5: return B return None # 问题遍历段 for row in grid: for cell in row: if get_side(cell) == U: x, y = cell.get_cords() print("X: " + str(x) + " Y: " + str(y)) #print("Color: " + colors[cell.get_color()])
解决方案
当前网格的存储结构为grid[x][y]:第一维索引对应X坐标,第二维对应Y坐标,原遍历直接按第一维循环,自然会先固定X再遍历所有Y,不符合需求。
有两种可直接落地的调整方式:
方案1:优先针对U面调整(改动最小)
U面的单元格范围是X∈[3,5],Y∈[0,3],直接替换原有遍历逻辑,先循环Y再循环X即可:
# 替换原有问题遍历段 # 先遍历Y(U面Y范围0-3) for y in range(0, 4): # 同一Y下遍历X(U面X范围3-5) for x in range(3, 6): cell = grid[x][y] if get_side(cell) == U: print(f"X: {x} Y: {y}")
输出顺序完全匹配要求:(3,0) → (4,0) → (5,0) → (3,1) → (4,1) → (5,1) ...
方案2:通用Y优先遍历(适配所有面的遍历需求)
如果后续要对魔方所有面都做Y优先遍历,可先转置网格,再沿用原遍历写法:
# 转置网格:将原grid[x][y]转为grid[y][x],不修改原网格结构 transposed_grid = [[grid[x][y] for x in range(len(grid))] for y in range(len(grid[0]))] # 遍历逻辑和原写法一致,自动按Y优先 for row in transposed_grid: for cell in row: if get_side(cell) == U: x, y = cell.get_cords() print(f"X: {x} Y: {y}")
内容的提问来源于stack exchange,提问作者hampani
相关产品推荐
相关产品推荐

