日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Something haunts me in Python

發布時間:2024/9/5 python 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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] = b

This 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。