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中的*運算采用的是淺復制。
?
@2: Slicing & Slice Assignment(http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice/10623352#10623352)
1. slicing:
b = a[0:2]This makes a copy of the slice of a and assigns it to b.
2. slice assignment:
a[0:2] = bThis replaces the slice of a with the contents of b.
Although the syntax is similar (I imagine by design!), these are two different operations.
?
@3:?針對上面silce assignment的例子進行進一步分析:
>>> a = [1, 4, 3] >>> b = [6, 7] >>> a[1:3] = b >>> a [1, 6, 7] >>> b [6, 7] >>> a[1] = 0 >>> a [1, 0, 7]此時b的值是多少?
>>> b [6, 7] >>>讓我們繼續:
代碼1:
>>> a[0:3] = b #長度不同,也允許 >>> a [6, 7] >>> b [6, 7] >>> a[1] = 1 #這種情況, 改變a不會影響b >>> a [6, 1] >>> b [6, 7] >>> b[1] = 8 #這種情況, 改變b不會影響a >>> b [6, 8] >>> a [6, 1]?
代碼2:
>>> b = [6, 7] >>> c = b >>> c [6, 7] >>> b[0] = 0 >>> b [0, 7] >>> c [0, 7] >>> c[0] = 10 >>> b [10, 7] >>> c [10, 7]比較代碼1和代碼2結果的不同,進一步理解slice assignment。
代碼3: slicing
>>> a = [1, 2, 3, 4] >>> b = a[:2] >>> a [1, 2, 3, 4] >>> b [1, 2] >>> b[0] = 9 >>> b [9, 2] >>> a [1, 2, 3, 4]?
?
轉載于:https://www.cnblogs.com/lxw0109/p/note_in_python.html
總結
以上是生活随笔為你收集整理的Something haunts me in Python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5.0:Spring-bean的加载
- 下一篇: jquery 选项卡实现