Something haunts me in Python

@1:  在查看"The Python Library Reference"(https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange)

的时候发现了这样的一段代码:

代码1:

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

  执行完lists[0].append(3)之后,程序将输出什么结果? [[3], [0], [0]]?

  正确答案是[[3], [3], [3]],让我们来看看Reference上的解释:

  This often haunts new Python programmers. 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:

代码2:

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

  补充:代码1中lists的三个元素都指向同一个空list,是因为:s * n, n * s --- n shallow copies of s concatenated,

即Python中的*运算采用的是浅复制。

 

Something haunts me in Python,布布扣,bubuko.com

Something haunts me in Python

上一篇:JAVA13-异常处理Exception


下一篇:Java接口