資訊內(nèi)容
python中怎么刪除列表中的元素
python刪除列表中元素的方法:1、使用remove()刪除單個(gè)元素,該函數(shù)可以刪除列表中某個(gè)值的第一個(gè)匹配項(xiàng);2、使用pop()刪除單個(gè)或多個(gè)元素,該函數(shù)根據(jù)索引來(lái)刪除元素,并返回該元素的值;3、使用del關(guān)鍵字根據(jù)索引來(lái)刪除元素。iQ5少兒編程網(wǎng)-https://www.pxcodes.com
iQ5少兒編程網(wǎng)-https://www.pxcodes.com
本教程操作環(huán)境:windows7系統(tǒng)、python3版,DELL G3電腦iQ5少兒編程網(wǎng)-https://www.pxcodes.com
python中關(guān)于刪除list中的某個(gè)元素,一般有三種方法:remove、pop、del:iQ5少兒編程網(wǎng)-https://www.pxcodes.com
1.remove: 刪除單個(gè)元素,刪除首個(gè)符合條件的元素,按值刪除
舉例說(shuō)明:iQ5少兒編程網(wǎng)-https://www.pxcodes.com
輸出iQ5少兒編程網(wǎng)-https://www.pxcodes.com
[1, 3, 4, 5, 2, 6]2.pop: 刪除單個(gè)或多個(gè)元素,按位刪除(根據(jù)索引刪除)iQ5少兒編程網(wǎng)-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> str.pop(1) #pop刪除時(shí)會(huì)返回被刪除的元素 >>> str [0, 2, 3, 4, 5, 6]>>> str2=['abc','bcd','dce'] >>> str2.pop(2) 'dce' >>> str2 ['abc', 'bcd']3.del:它是根據(jù)索引(元素所在位置)來(lái)刪除iQ5少兒編程網(wǎng)-https://www.pxcodes.com
舉例說(shuō)明:iQ5少兒編程網(wǎng)-https://www.pxcodes.com
>>> str=[1,2,3,4,5,2,6] >>> del str[1] >>> str [1, 3, 4, 5, 2, 6]>>> str2=['abc','bcd','dce'] >>> del str2[1] >>> str2 ['abc', 'dce']除此之外,del還可以刪除指定范圍內(nèi)的值。iQ5少兒編程網(wǎng)-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> del str[2:4] #刪除從第2個(gè)元素開(kāi)始,到第4個(gè)為止的元素(但是不包括尾部元素) >>> str [0, 1, 4, 5, 6]del 也可以刪除整個(gè)數(shù)據(jù)對(duì)象(列表、集合等)iQ5少兒編程網(wǎng)-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> del str >>> str #刪除后,找不到對(duì)象 Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> str NameError: name 'str' is not defined注意:del是刪除引用(變量)而不是刪除對(duì)象(數(shù)據(jù)),對(duì)象由自動(dòng)垃圾回收機(jī)制(GC)刪除。iQ5少兒編程網(wǎng)-https://www.pxcodes.com
補(bǔ)充: 刪除元素的變相方法iQ5少兒編程網(wǎng)-https://www.pxcodes.com
s1 = (1, 2, 3, 4, 5, 6) s2 = (2, 3, 5) s3 = []for i in s1: if i not in s2: s3.append(i)print('s1_1:', s1) s1 = s3print('s2:', s2)print('s3:', s3)print('s1_2:', s1)相關(guān)推薦:Python3視頻教程
以上就是python中怎么刪除列表中的元素的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注少兒編程網(wǎng)其它相關(guān)文章!iQ5少兒編程網(wǎng)-https://www.pxcodes.com
- 上一篇
python return用法是什么
簡(jiǎn)介pythonreturn用法:1、返回函數(shù)的返回值;2、終止程序的運(yùn)行,提前退出,例如,當(dāng)函數(shù)內(nèi)有錯(cuò)誤發(fā)生時(shí),使用return可以終止函數(shù)的運(yùn)行。本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,DELLG3電腦,該方法適用于所有品牌電腦。pythonreturn用法:(1)、返回函數(shù)的返
- 下一篇
python 怎么求平均值
簡(jiǎn)介python求平均值的方法:首先新建一個(gè)python文件;然后初始化sum總和的值;接著循環(huán)輸入要計(jì)算平均數(shù)的數(shù),并計(jì)算總和sum的值;最后利用“總和/數(shù)量”的公式計(jì)算出平均數(shù)即可。本文操作環(huán)境:Windows7系統(tǒng),python3.5版本,DellG3電腦。首先我們先來(lái)了解一下計(jì)算平均數(shù)的IPO模
