詳解Python3中的Sequence type的使用

來源:互聯網
上載者:User
其實本來是要reverse一下list的,就去查了一下list[::-1]是什麼意思,發現還有很多要注意的地方,所以就記一下。
主要是參照https://docs.python.org/3/library/stdtypes.html?highlight=list#list

首先Sequence type有三種

  1. list
  2. tuple
  3. range

slice

[i:j:k]表示的是slice of s from i to j with step k, 對三種類型都有用

>>> a = [1, 2, 3]>>> a[::-1][3, 2, 1]>>> a = (1, 2, 3)>>> a[::-1](3, 2, 1)>>> a = range(3)>>> a[::-1]range(2, -1, -1)

range中參數是range(start, stop[, step])
initialize a list

s * n表示的是n shallow copies of s concatenated
注意是淺拷貝哦,所以會有如下情況

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

如果元素不是對象的話就沒關係

>>> lists = [0] * 3>>> lists[0, 0, 0]>>> lists[0] = 1>>> lists[1, 0, 0]

正確的初始化嵌套list的方法應該是

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

concatenation pitfall

(感覺還是英文說的清楚些,這一點跟Java是一樣的)
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.