首页 > 编程语言 > 详细

Something haunts me in Python

时间:2014-04-24 01:02:53      阅读:563      评论:0      收藏:0      [点我收藏+]

@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

原文:http://www.cnblogs.com/lxw0109/p/note_in_python.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!