python——列表

來源:互聯網
上載者:User

標籤:第一個   .so   remove   reserve   常用   iter   sort   str   解析   

列表的建立

1、普通方法建立列表

list = []


2、列表解析、列表推導式

使用列表解析比使用普通方法的速度幾乎可以快1倍。因此推薦使用列表解析。

文法

[expression for iter_val in iterable if cond_expr]
要求:列出1~10所有數位平方>>>L = [ i**2 for i in range(1,11)]>>>print L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

列表的更新

>>> list = [1,2,3]>>> list.append(‘4‘)#添加清單項目>>> list[1, 2, 3, ‘4‘]>>> del list[3]#刪除清單項目>>> list[1, 2, 3]
>>> list1 = [1,2,3]>>> list2 = [4,5,6]>>> list1.extend(list2)#一次性追加多個值>>> list1[1, 2, 3, 4, 5, 6]
>>> list = [1,2,2,3,4]>>> list.remove(2)#移除列表中某個值的第一個匹配項>>> list[1, 2, 3, 4]>>> list.pop()#移除列表中的一個元素(預設最後一個元素),並且返回該元素的值4>>> list[1, 2, 3]
>>> list = [1,2,3]>>> list.insert(1,4)#插入>>> list[1, 4, 2, 3]

列表常用方法

list.index()

#尋找元素所在位置>>> list = [1,2,3]>>> list.index(2)1

list.count()

list.reserve()

#反轉>>> list = [1,2,3]>>> list.reverse()>>> list[3, 2, 1]

list.clear()

#清空列表>>> list = [1,2,3]>>> list.clear()>>> list[]

list.sort()

>>> list = [1,3,2,6,5]>>> list.sort()#列表排序>>> list[1, 2, 3, 5, 6]

 

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.