python---list

來源:互聯網
上載者:User

標籤:地址   技術   com   通過   png   記憶體   插入   extend   elb   

一、列表

  作用:存放人員資訊,多個名稱等等

  定義:[]內以逗號分隔,按照索引,存放各種資料類型,每個位置代表一個元素。list()也可以定義。

  以下是列表相關命令:

    

 

    

###建立listL1 = [] #定義空列表L2 = [‘a‘,‘b‘,‘c‘,1,2,3] #取值用索引的方式 0-5L3 = [1,2,3,[‘a‘,‘b‘]] #嵌套列表L4 = list()   #定義空列表###查詢print(L2[0])  #通過索引尋找第0個元素print(L2[-1])  #通過索引尋找從右邊開始取值,右邊順序為:-1,-2,-3.。。。print(L3[-1][0])  #取嵌套裡面的第一個值print(L2.index(‘a‘)) #返回指定元素的索引值,從左至右尋找,有多個時只返回從左至右尋找的第一個。print(L2.count(‘a‘)) #統計元素的個數。##切片print(L2[0:3])   #返回從索引0到3的元素,但不包括3,顧頭不顧尾print(L2[3:])    #返回從索引3到最後print(L2[:6:2])   #返回0到6,但不包括6 的步長為2(每隔一個元素,去一個值)##增加L2.append(‘A‘)   #追加到最後一個L2.insert(3,‘B‘) #插入,在清單索引為3的位置插入一個值B##修改L2[3] = [‘Baby‘]   #把索引為3的元素修改為babyL2[3:5] = [‘Angelbaby‘]  #把索引3到5的元素改為Angelbabt,不夠的元素自動增加##刪除L2.pop() #刪除最後一個元素L2.pop(1) #刪除指定索引元素x = L2.pop(3) # 把l2刪除的值賦值給X##隊列:先進先出queue_l=[]##入隊# queue_l.append(‘first‘)# queue_l.append(‘second‘)# queue_l.append(‘third‘)# print(queue_l)##出隊# print(queue_l.pop(0))# print(queue_l.pop(0))# print(queue_l.pop(0))##堆棧:先進後出,後進先出l=[]#入棧l.append(‘first‘)l.append(‘second‘)l.append(‘third‘)#出棧print(l)print(l.pop())print(l.pop())print(l.pop())L2.remove(‘A‘) #刪除元素A,從左至右第一個Adel L2[4] #刪除指定索引的元素,del是python全域刪除方法del L2[3:7] #刪除多個元素##迴圈L2 = [‘a‘,‘b‘,‘c‘,1,2,3]for i in L2:    print(i)   #列印L2中的每一個值for i in range(10):    print(i)#while和for迴圈的區別,while可以定義成死迴圈,沒有邊界。for迴圈是有邊界的。##排序n = [‘a‘,‘e‘,‘w‘,‘g‘,12,‘u‘,‘o‘,76,32,56]>>>n.sort()‘‘‘Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: ‘<‘ not supported between instances of ‘int‘ and ‘str‘‘‘‘n = [‘a‘,‘e‘,‘U‘,‘‘w‘,‘g‘,‘u‘,‘o‘,‘A‘]n.sort()   #排序方式是按照ASCII碼錶進行排序n.reverse() #反向排序##兩個列表相加list_1 = [‘a‘,‘b‘,‘c‘,1,2,3]list_2 = [1,2,3,[‘a‘,‘b‘]]print(list_1+list_2)list_1.extend(list_2) #extend() 擴充list_1.clear()   #清空列表list_3=list_1.copy() #完全獨立的一個記憶體位址。

 

python---list

聯繫我們

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