添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

输出结果如下:

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

是不是很惊讶?!
这个问题真的是折磨我一个中午,去网上一搜,官方文档中给出的说明是这样的:

Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]

也就是说matrix = [array] * 3操作中,只是创建3个指向array的引用,所以一旦array改变,matrix中3个list也会随之改变。

2.创建二维数组的办法

2.1 直接创建法

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

简单粗暴,不过太麻烦,一般不用。

2.2 列表生成式法

test = [[0 for i in range(m)] for j in range(n)]

学会使用列表生成式,终生受益。不会的可以去列表生成式 - 廖雪峰的官方网站学习。

2.3 使用模块numpy创建

import numpy as np
test = np.zeros((m, n), dtype=np.int)

关于模块numpy.zeros的更多知识,可以去numpy.zeros(np.zeros)使用方法--python学习笔记31看看。