python二维数组遍历
时间: 2023-06-23 10:10:13 浏览: 112
在Python中,可以使用嵌套的for循环来遍历二维数组。例如,假设有一个3行4列的二维数组arr:
``` python
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
```
那么可以使用以下代码遍历这个二维数组中的所有元素:
``` python
for i in range(len(arr)):
for j in range(len(arr[i])):
print(arr[i][j])
```
其中,外层的for循环用来遍历每一行,内层的for循环用来遍历每一行中的元素。在这个例子中,输出的结果将是:
```
1
2
3
4
5
6
7
8
9
10
11
12
```
当然,也可以使用更简单的方式来遍历二维数组,例如使用列表推导式:
``` python
[element for row in arr for element in row]
```
这行代码的含义是先遍历每一行,再遍历每一行中的元素,最终将所有元素放入一个新的列表中。这个新列表的元素顺序与原二维数组中的元素顺序相同。
相关问题
python 二维数组遍历
以下是两种Python遍历二维数组的方法:
1. 使用嵌套循环遍历二维数组
```python
world = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
for i in range(len(world)):
for j in range(len(world[i])):
print(world[i][j])
```
2. 使用numpy库遍历二维数组
```python
import numpy as np
world = np.zeros([3, 3])
for i in range(world.shape[0]):
for j in range(world.shape[1]):
print(world[i][j])
```
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]
```