python_資料類型——,python資料類型

來源:互聯網
上載者:User

python_資料類型——,python資料類型

names = ['one','two','three','four','five']#列表切片print(names[0:])    #['one', 'two', 'three', 'four', 'five']print(names[1:])    #['two', 'three', 'four', 'five']print(names[1:-1])    #['two', 'three', 'four']print(names[1:-1:2])    #['two', 'four'],從左至右隔一個取print(names[1::2])     #['two', 'four']print(names[1::-2])    #['two'],代表從第二個開始,從右往左隔一個取print(names[3::-1])    #['four', 'three', 'two', 'one'],即從第四個開始,從右往左取#添加names.append('kt')    #添加,自動在列表末尾添加names.insert(1,'lx')    #在第二位處插入#修改,直接對索引位置賦值names[1] = 'glx'    #將第二位的改為glxnames[2:4] = ['b','c']    #將3,4位的改為'b','c'    因為取出的索引是列表,所以要用列表替換#刪除names.remove('b')    #remove方法刪除要指定索引內容delete = names.pop(2)    #刪除第三位的內容,pop方法中retrun可以返回刪除的內容,即傳回值為刪除的元素print(delete)    #列印出pop刪除的內容為cdel delete    #直接將delete整個變數刪除#其他動作#方法count,計算某個元素出現的次數print(names.count('glx'))    #顯示'glx'出現的次數#方法extend,在列表a後面添加列表ba = [1,2,3]b = [4,5,6]a.extend(b)print(a)    #[1, 2, 3, 4, 5, 6]print(b)    #[4, 5, 6]#方法index,尋找元素在列表中的位置print(names)    #['one', 'glx', 'four', 'five', 'kt']print(names.index('kt'))    #4,得出kt的位置在第五位c = [1,2,3,2,3]print(c.index(2))    #index預設輸出捕捉到的首個2的位置#方法reverse翻轉列表names.reverse()    #['kt', 'five', 'four', 'glx', 'one']print(names)#方法sort對列表進行排序,按ASCII碼順序從小到大x = [2,5,8,6,4,5]x.sort()    #[2, 4, 5, 5, 6, 8]x1 = x.sort()    #None,即sort方法中沒有寫return,所以沒有傳回值,所以顯示Noneprint(x)    #列表方法中,只有pop有傳回值print(x1)y = ['D','f','a','c']print(y.sort())    #Noney.sort()    #['D', 'a', 'c', 'f']print(y)y.sort(reverse=True)    #['f', 'c', 'a', 'D'],排序,並且逆序print(y)
  小結:

在切片中:[start:end:step]

start代表起始索引位置
end代表終止索引位置,如果為空白則代表邊界,可以是作左邊界也可以是右邊界
step代表步進,同時控制方向

  總結:

查:

  索引,下標  切片  .count('元素') #尋找元素在列表中出現的次數  .index('元素') #尋找元素在列表中第一次出現的位置

刪:

.pop('索引') #刪除索引位置的元素,有傳回值.remove('元素') #刪除列表中指定的元素del #可直接刪除整個列表.clear() #清空整個列表

增:

.append('新元素') #在列表末尾添加新元素.insert(索引,'新元素') #在索引位置插入新元素.extend(list1,list2) #在list1後面擴充list2

改:

list['索引']='新元素'list[index1:index2] = list #如果取出的是列表,則傳入的也要是列表,否則置空的將刪除

排序:

.sort() #按ASCII碼順序,由小到大排序.sort(reverse=True) #逆序.reverse() #逆序排序

  

聯繫我們

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