关于列表的浅复制
Sample:
>>> 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:
[[]]是一个含有空列表的列表, [[]]*3 中所有的元素都指向空列表元素(即本身也是列表的元素[])。对lists元素中的任何修改都会修改此空列表元素(即修改lists中的每个元素,)。如果想创建一个不同的列表可以使用下面的方式:
>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
lists列表中每个元素[]都是独立的元素,所以修改任何一个元素都不会影响其他的元素。第一个例子中的如果为lists中每个元素赋值,将会切断列表键对[]的引用,不会影响其他元素的值。