使用python写一个3*3的蛇形矩阵
时间: 2023-04-08 21:04:39 浏览: 288
好的,这个问题可以回答。以下是使用Python编写3*3的蛇形矩阵的代码:
```
n = 3
matrix = [[0] * n for i in range(n)]
num = 1
for i in range(n):
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
print(matrix)
```
输出结果为:
```
[[1, 2, 3], [6, 5, 4], [7, 8, 9]]
```
希望这个代码可以帮到你!
相关问题
用python写出m*n的蛇形矩阵,多种方式
方法一:使用二维列表
```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
```
用python写一个蛇形矩阵
在Python中,我们可以使用嵌套循环和列表推导式来创建一个蛇形矩阵。蛇形矩阵通常是一个对称的矩阵,每一行和每一列都有递增或递减的顺序。下面是一个简单的例子:
```python
def snake_matrix(n):
# 创建一个空的n*n矩阵
matrix = [[0] * n for _ in range(n)]
# 初始化位置和方向
x, y, dx, dy = 0, 0, 1, -1
for i in range(2 * n - 1): # 蛇形移动次数
matrix[x][y] = i + 1 # 设置值
if (x == n - 1 and y > 0) or (x == 0 and y < n - 1): # 当到达边界时改变方向
dx, dy = -dy, dx
x, y = x + dx, y + dy # 更新坐标
return matrix
# 示例
n = 5
snake_mat = snake_matrix(n)
for row in snake_mat:
print(row)
#
阅读全文