目的:
想生成一个[[],[],[]] 这样的列表,
所以就 [[]]*3 这样做了,但是这样做会有问题,这样list中的三个list其实是同一个list。
例如:a=[[]]*3,然后a[0].append(1),
然后a就变成这样了:[[1],[1],[1]]
验证一下,发现表达式 a[0] is a[1] 的值为True。
如何解决呢,可以用列表生成器:a=[[] for i in range(3)]
这应该像是值类型和引用类型的区别,但是翻看python的文档时没发现有类似的说法,不过在翻看文档时发现里面提到了这个情形:
https://docs.python.org/3.6/library/stdtypes.html
内容摘录如下:
Note that items in the sequence s are not copied; they are referenced multiple times. 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 references 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]]
原文地址:https://www.cnblogs.com/vanwoos/p/9217130.html