python學習--列表

來源:互聯網
上載者:User

標籤:列表

一:定義

python的列表對象是python中最通用的序列。列表是一個任意類型的對象的位置相關的有序集合,它沒有固定的大小。通過對位移量進行賦值以及其他各種列表的方法進行調用,確實可以修改列表的大小。

二:列表的操作

1:求長度

>>> L=[123, ‘dddd‘,12.5]>>> len(L)3

2:索引和切片

>>> L[0]123>>> L[:-1][123, ‘dddd‘]>>> L+[‘kai‘,12,‘dd‘][123, ‘dddd‘, 12.5, ‘kai‘, 12, ‘dd‘]>>> L[123, ‘dddd‘, 12.5]>>> 

3:增加列表

>>> L.append(‘jj‘)  #預設加在列表的最後>>> L[123, ‘dddd‘, 12.5, ‘jj‘]>>> L.insert(1,‘ww‘)>>> L[123, ‘ww‘, 12.5]

4:減小列表

>>> L.pop(3)‘jj‘>>> L[123, ‘dddd‘, 12.5][123, ‘ww‘, 12.5]>>> L.remove(‘ww‘)>>> L>>> [123, 12.5]

5:排序,反轉

>>> M=[11, 45, 56,23,78] >>> M.sort()   #也可以對字元排序>>> M[11, 23, 45, 56, 78]>>> M.reverse()>>> M[78, 56, 45, 23, 11]
三:邊界檢查
列表雖然沒有固定大小,但python不允許引用不存在的元素。超出列表末尾之外的索引總是會導致錯誤,對列表末尾範圍之外賦值也是如此。
四:列表嵌套
>>> L=[[1,2,3],[4,5,6],[7,8,9]]>>> L[[1, 2, 3], [4, 5, 6], [7, 8, 9]]>>> L[1][4, 5, 6]>>> L[1][2]6
五:列表解析

列表解析源於集合的概念。它是一種通過對序列中的每一項運行一個運算式來建立一個新列表的方法,從左至右,每次一個。
1:提取矩陣的某一列

>>> l=[row[2] for row in L]>>> l[3, 6, 9]

2:提取矩陣的某一列並加一

>>> l=[row[1] +1 for row in L]>>> l[3, 6, 9]

3:提取矩陣的某一列為偶數的數字

>>> l=[row[1] for row in L if row[1]%2==0]>>> l[2, 8]

4:取對角線上的數

>>> diag=[L[i][i] for i in [0,1,2]]>>> diag[1, 5, 9]

5:

>>> doubles=[c * 2 for c in ‘sap‘]>>> doubles[‘ss‘, ‘aa‘, ‘pp‘]

6:

>>> G=(sum(row) for row in L)>>> next(G)6>>> next(G)15>>> next(G)24>>> list(map(sum,L))[6, 15, 24]>>> {sum(row) for row in L}{24, 6, 15}>>> {i : sum(L[i]) for i in range(3)}{0: 6, 1: 15, 2: 24}

python學習--列表

聯繫我們

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