列表中 Python 错误中的幻方,但 Numpy 数组中没有
Magic Square in Python error in Lists but not in Numpy arrays
我有这两个版本的程序可以生成奇数阶幻方,
1.使用 numpy 数组:
import numpy as np
N = 5
magic_square = np.zeros((N, N), dtype=int)
n = 1
i, j = 0, N // 2
while n <= N ** 2:
magic_square[i, j] = n
n += 1
newi, newj = (i - 1) % N, (j + 1) % N
if magic_square[newi, newj]:
i += 1
else:
i, j = newi, newj
print(magic_square)
2。使用列表
N = 5
magic_square = [[0] * N] * N
n = 1
i, j = 0, N // 2
while n <= N ** 2:
magic_square[i][j] = n
n += 1
newi, newj = (i - 1) % N, (j + 1) % N
if magic_square[newi][newj]:
i += 1
else:
i, j = newi, newj
print(magic_square)
但是使用列表的会给出一个 IndexError: list index out of range for line , magic_square[i][j] = n
np 数组和列表的索引有什么不同吗?
如果是,那么如何更正包含列表的代码?
正如 hpaulj 所说,不要使用 [[0]*N]*N]
>>> l = [[0]*5]*5
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0]] # same as above list
>>> l[0][0] = 5
[[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0]]
使用
magic_square = [[0 for i in range(N)] for i in range(N)]
我有这两个版本的程序可以生成奇数阶幻方,
1.使用 numpy 数组:
import numpy as np
N = 5
magic_square = np.zeros((N, N), dtype=int)
n = 1
i, j = 0, N // 2
while n <= N ** 2:
magic_square[i, j] = n
n += 1
newi, newj = (i - 1) % N, (j + 1) % N
if magic_square[newi, newj]:
i += 1
else:
i, j = newi, newj
print(magic_square)
2。使用列表
N = 5
magic_square = [[0] * N] * N
n = 1
i, j = 0, N // 2
while n <= N ** 2:
magic_square[i][j] = n
n += 1
newi, newj = (i - 1) % N, (j + 1) % N
if magic_square[newi][newj]:
i += 1
else:
i, j = newi, newj
print(magic_square)
但是使用列表的会给出一个 IndexError: list index out of range for line , magic_square[i][j] = n
np 数组和列表的索引有什么不同吗?
如果是,那么如何更正包含列表的代码?
正如 hpaulj 所说,不要使用 [[0]*N]*N]
>>> l = [[0]*5]*5
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0], # same as above list
[0, 0, 0, 0, 0]] # same as above list
>>> l[0][0] = 5
[[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0],
[5, 0, 0, 0, 0]]
使用
magic_square = [[0 for i in range(N)] for i in range(N)]