遍历二维数组 python
时间: 2025-05-02 19:49:38 浏览: 32
### Python 中遍历二维数组的方法
在 Python 中,可以通过多种方式来遍历二维数组。以下是几种常见的方法及其具体实现:
#### 1. 使用嵌套循环逐行逐列访问
这是最基础的方式,通过两个 `for` 循环分别迭代外层列表和内层子列表。
```python
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in array:
for element in row:
print(element, end=" ")
```
这种方式可以按照行优先的顺序逐一打印出每个元素[^1]。
---
#### 2. 螺旋遍历二维数组
螺旋遍历是一种特殊的遍历模式,它按照从外到内的顺时针方向逐步提取元素。下面是一个具体的实现例子:
```python
class Solution(object):
def spiralArray(self, array):
if not array or not array[0]:
return []
result = []
top, bottom = 0, len(array) - 1
left, right = 0, len(array[0]) - 1
while top <= bottom and left <= right:
# 左至右
for col in range(left, right + 1):
result.append(array[top][col])
top += 1
# 上至下
for row in range(top, bottom + 1):
result.append(array[row][right])
right -= 1
if top <= bottom:
# 右至左
for col in range(right, left - 1, -1):
result.append(array[bottom][col])
bottom -= 1
if left <= right:
# 下至上
for row in range(bottom, top - 1, -1):
result.append(array[row][left])
left += 1
return result
solution = Solution()
print(solution.spiralArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
```
上述代码实现了从左上角开始沿顺时针方向螺旋读取二维数组的功能[^2]。
---
#### 3. 对角线遍历二维数组
对角线遍历是指沿着矩阵的主对角线或次对角线依次访问元素。以下是对角线遍历的一个通用解决方案:
```python
def findDiagonalOrder(matrix):
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
result = []
for s in range(m + n - 1):
if s % 2 == 0: # 偶数斜线,从下往上
i = min(s, m - 1)
j = s - i
while i >= 0 and j < n:
result.append(matrix[i][j])
i -= 1
j += 1
else: # 奇数斜线,从上往下
j = min(s, n - 1)
i = s - j
while j >= 0 and i < m:
result.append(matrix[i][j])
i += 1
j -= 1
return result
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(findDiagonalOrder(matrix)) # 输出:[1, 2, 4, 7, 5, 3, 6, 8, 9]
```
该算法能够处理任意大小的矩形矩阵,并支持两种不同的对角线方向交替切换[^4]。
---
#### 4. 列优先遍历
除了传统的行优先遍历之外,还可以采用列优先的方式来访问二维数组中的数据项。
```python
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
num_cols = max(len(row) for row in array)
for c in range(num_cols):
for row in array:
if c < len(row):
print(row[c], end=' ')
```
这种方法先固定某一列再移动指针指向不同行的位置。
---
### 总结
以上介绍了四种主要的 Python 遍历二维数组的技术——标准嵌套循环、螺旋遍历、对角线扫描以及列主导检索法。每种技术都有其特定的应用场景,在实际开发过程中可以根据需求灵活选用合适的策略完成任务。
阅读全文
相关推荐


















