用python写出m*n的蛇形矩阵,多种方式
时间: 2024-01-26 11:39:17 浏览: 63
方法一:使用二维列表
```python
def snake_matrix(m, n):
matrix = [[0] * n for _ in range(m)]
num = 1
for i in range(m):
if i % 2 == 0:
for j in range(n):
matrix[i][j] = num
num += 1
else:
for j in range(n - 1, -1, -1):
matrix[i][j] = num
num += 1
return matrix
```
方法二:使用一维列表
```python
def snake_matrix(m, n):
matrix = [0] * (m * n)
num = 1
for i in range(m):
if i % 2 == 0:
for j in range(n):
matrix[i * n + j] = num
num += 1
else:
for j in range(n - 1, -1, -1):
matrix[i * n + j] = num
num += 1
return [matrix[i * n:(i + 1) * n] for i in range(m)]
```
方法三:使用numpy数组
```python
import numpy as np
def snake_matrix(m, n):
matrix = np.zeros((m, n), dtype=int)
num = 1
for i in range(m):
if i % 2 == 0:
for j in range(n):
matrix[i][j] = num
num += 1
else:
for j in range(n - 1, -1, -1):
matrix[i][j] = num
num += 1
return matrix
```
阅读全文