python用while对二维数组进行遍历
时间: 2024-01-17 11:05:53 浏览: 195
可以使用while嵌套循环对二维数组进行遍历,示例代码如下:
```
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(array):
j = 0
while j < len(array[i]):
print(array[i][j])
j += 1
i += 1
```
这段代码会打印出二维数组中每一个元素的值。其中,外层的while循环控制行数,内层的while循环控制列数。
相关问题
python二维数组回形遍历
以下是Python实现二维数组回形遍历的代码示例:
```python
def spiralOrder(matrix):
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
left, right, top, bottom = 0, n - 1, 0, m - 1
res = []
while left <= right and top <= bottom:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = spiralOrder(matrix)
print(result) # 输出:[1, 2, 3, 6, 9, 8, 7, 4, 5]
```
螺旋遍历二维数组python
### 螺旋遍历二维数组
为了实现螺旋遍历二维数组,在 Python 中可以采用一种方法来模拟顺时针方向访问矩阵中的每一个元素。下面是一个具体的例子:
```python
def spiral_traverse(matrix):
result = []
if not matrix or not matrix[0]:
return result
row_begin, row_end = 0, len(matrix) - 1
col_begin, col_end = 0, len(matrix[0]) - 1
while row_begin <= row_end and col_begin <= col_end:
# Traverse Right
for i in range(col_begin, col_end + 1):
result.append(matrix[row_begin][i])
row_begin += 1
# Traverse Down
for i in range(row_begin, row_end + 1):
result.append(matrix[i][col_end])
col_end -= 1
if row_begin <= row_end:
# Traverse Left
for i in range(col_end, col_begin - 1, -1):
result.append(matrix[row_end][i])
row_end -= 1
if col_begin <= col_end:
# Traverse Up
for i in range(row_end, row_begin - 1, -1):
result.append(matrix[i][col_begin])
col_begin += 1
return result
```
此函数接收一个二维列表 `matrix` 并返回一个新的列表,其中包含了按照螺旋顺序排列的原始矩阵的所有元素[^1]。
阅读全文
相关推荐















