Python创建二维数组的一个坑

m = n = 3
test = [[0] * m] * n
print("test =", test)

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

是不是看起来没有一点问题?其实不然,往下看:

m = n = 3
test = [[0] * m] * n
print("test =", test)

test[0][0] = 22
print("test =", test)

test = [[22, 0, 0], [22, 0, 0], [22, 0, 0]]

是不是很惊讶?!其实这种创建二维list的方式会共享一个内存地址。

创建二维数组的正确操作:

  • 直接创建法
test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]

虽然这是最直接明了的方法,但是太麻烦,太粗暴。

  • 列表生成式法
test = [[0 for i in range(m)] for j in range(n)]

这种方法是最为推荐的,不用导入额外的库。

  • 使用模块numpy创建
import numpy as np
test = np.zeros((m, n), dtype=np.int)

猜你喜欢

转载自blog.csdn.net/Frank_LJiang/article/details/106266342