python用while对二维数组进行遍历
时间: 2024-01-17 19:05:53 浏览: 42
可以使用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]
```
使用while语句遍历一个简单的二维数组
假设我们有一个二维数组arr,代码如下:
```python
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
我们可以使用两个嵌套的while循环来遍历这个二维数组,代码如下:
```python
i = 0
while i < len(arr):
j = 0
while j < len(arr[i]):
print(arr[i][j])
j += 1
i += 1
```
在这个代码中,我们使用i和j两个变量分别表示当前遍历到的行和列。外层的while循环控制行数,内层的while循环控制列数。在每一次循环中,我们使用arr[i][j]来访问当前遍历到的元素,并输出它的值。最后,我们分别将i和j加1,以便进入下一个循环。
运行上面的代码,输出如下:
```
1
2
3
4
5
6
7
8
9
```