python處理列表的部分元素的實(shí)例詳解
1、處理列表的部分元素稱之為切片,創(chuàng)建切片,可指定要使用的第一個(gè)元素和最后一個(gè)元素的索引。
2、這讓Python創(chuàng)建一個(gè)始于第一個(gè)元素,終止于最后一個(gè)元素的切片,即復(fù)制整個(gè)列表。
實(shí)例
names = ['zhang_san','chen_cheng','li_hong','liu_li','chen_yu'] print(names[0:3]) print(names[0:-1]) print(names[:]) print(names[-1]) print(names[-3:]) 負(fù)數(shù)索引返回離列表末尾相應(yīng)距離的元素,要輸出名單上的最后三名隊(duì)員,可使用切片names[-3:] 與函數(shù)range()一樣, Python在到達(dá)你指定的第二個(gè)索引前面的元素后停止 ['zhang_san', 'chen_cheng', 'li_hong'] ['zhang_san', 'chen_cheng', 'li_hong', 'liu_li'] ['zhang_san', 'chen_cheng', 'li_hong', 'liu_li', 'chen_yu'] chen_yu ['li_hong', 'liu_li', 'chen_yu']
實(shí)例擴(kuò)展:
列表類似于java中的數(shù)組,用方括號(hào)表示,逗號(hào)分隔其中的元素
#賦值、打印 children_names = ['杜子騰','杜小月','杜小星','杜小陽(yáng)','杜小花'] print(children_names)
運(yùn)行結(jié)果:
['杜子騰', '杜小月', '杜小星', '杜小陽(yáng)', '杜小花']
訪問(wèn)其中的某一個(gè)元素
children_names = ['杜子騰','杜小月','杜小星','杜小陽(yáng)','杜小花'] print(children_names[2])#按照索引,打印其中的某一個(gè)元素,索引從0開(kāi)始 print(children_names[-1]) #按照索引,打印最后一個(gè)元素,依次類推-1,-2,-3... print(len(children_names)) #獲取列表的長(zhǎng)度
運(yùn)行結(jié)果:
杜小星
杜小花
5
修改元素
children_names = ['杜子騰','杜小月','杜小星','杜小陽(yáng)','杜小花'] children_names[2]='杜小懶' #按照索引,直接覆蓋賦值 print(children_names)
運(yùn)行結(jié)果:
['杜子騰', '杜小月', '杜小懶', '杜小陽(yáng)', '杜小花']
添加元素
children_names = ['杜子騰','杜小月','杜小星','杜小陽(yáng)','杜小花'] children_names.append("杜小懶2號(hào)") #列表尾部追加 children_names.insert(0,"杜小杜")#按照索引位置,插入元素 print(children_names)
運(yùn)行結(jié)果:
['杜小杜', '杜子騰', '杜小月', '杜小星', '杜小陽(yáng)', '杜小花', '杜小懶2號(hào)']
刪除元素
- del和pop的使用區(qū)別在于,刪除以后還使用不使用【依據(jù)索引】
- 按值刪除,remove
del children_names[0] #按照索引,徹底刪除元素 children_pop = children_names.pop() #準(zhǔn)確說(shuō)是,彈出列表尾部元素【也可以指定索引】,賦值給一個(gè)變量,暫時(shí)保存 children_names.remove("杜小懶2號(hào)") #若存在重復(fù)數(shù)據(jù),則只刪除第一個(gè)
列表的排序
- 使用sort按照字母順序永久排序
- 使用sorted按照字母順序,對(duì)列表進(jìn)行臨時(shí)排序
- 倒著打印列表
visitors = ['a1','b1','c1','d1','e'] visitors.sort() #按字母順序,排序,不可逆 visitors.sort(reverse=True) #按字母倒序,不可逆 print(sorted(visitors)) #臨時(shí)排序,不影響現(xiàn)有數(shù)據(jù)順序 print(sorted(visitors,reverse=True)) #臨時(shí)倒序排序,不影響現(xiàn)有數(shù)據(jù)順序 visitors.reverse() #直接倒序,跟字母順序無(wú)關(guān),可逆,再執(zhí)行一次即可
運(yùn)行結(jié)果:
['a1', 'b1', 'c1', 'd1', 'e']
['e', 'd1', 'c1', 'b1', 'a1']
到此這篇關(guān)于python處理列表的部分元素的實(shí)例詳解的文章就介紹到這了,更多相關(guān)python處理列表的部分元素內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。