Python常用列表資料結構小結_python

來源:互聯網
上載者:User

本文匯總了Python列表list一些常用的對象方法,可供初學者參考或查詢,具體如下:

1.list.append(x)

把元素x添加到列表的結尾,相當於a[len(a):] =[x],代碼如下:

>>> a=[1,2,3,4,5]>>> a[1, 2, 3, 4, 5]>>> a.append(-2)>>> a[1, 2, 3, 4, 5, -2]

2. list.extend(L)

將一個列表中的所有元素都添加到另一個列表中,相當於 a[len(a):] = L,代碼如下:

>>> a[1, 2, 3, 4, 5, -2]>>> L=[5,9,7]>>> L[5, 9, 7]>>> a.extend(L)>>> a[1, 2, 3, 4, 5, -2, 5, 9, 7]

3. list.insert(i,x)

將元素x,插到索引號i之前,代碼如下:

>>> a[1, 2, 3, 4, 5, -2, 5, 9, 7]>>> a.insert(0,-3)>>> a[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7]>>> a.insert(len(a),10)>>> a[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]

4. list.remove(x)

刪除元素x(第一次出現的),代碼如下:

>>> a[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]>>> a.append(1)>>> a[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]>>> a.remove(1)>>> a[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]

5. list.count(x)

計算元素x出現的次數,代碼如下:

>>> a[-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]>>> a.count(3)1

6. list.sort()

對列表元素進行排序,代碼如下:

>>> a.sort()>>> a[-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]

7. list.reverse()

倒排列表中元素,代碼如下:

>>> a[-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]>>> a.reverse()>>> a[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]

8. list.index(x)

返回表中第一個出現值為x的索引,代碼如下:

>>> a[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]>>> a.index(9)1

9. list.pop(i)

從列表指定位置i刪除元素,並將此元素返回,若未指定位置則刪除列表最後一位元素,並將此元素返回。代碼如下:

>>> a[10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]>>> a.pop(0)10>>> a[9, 7, 5, 5, 4, 3, 2, 1, -2, -3]>>> a.pop()-3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.