資訊內容
python中怎么刪除列表中的元素
python刪除列表中元素的方法:1、使用remove()刪除單個元素,該函數可以刪除列表中某個值的第一個匹配項;2、使用pop()刪除單個或多個元素,該函數根據索引來刪除元素,并返回該元素的值;3、使用del關鍵字根據索引來刪除元素。iQ5少兒編程網-https://www.pxcodes.com
iQ5少兒編程網-https://www.pxcodes.com
本教程操作環境:windows7系統、python3版,DELL G3電腦iQ5少兒編程網-https://www.pxcodes.com
python中關于刪除list中的某個元素,一般有三種方法:remove、pop、del:iQ5少兒編程網-https://www.pxcodes.com
1.remove: 刪除單個元素,刪除首個符合條件的元素,按值刪除
舉例說明:iQ5少兒編程網-https://www.pxcodes.com
輸出iQ5少兒編程網-https://www.pxcodes.com
[1, 3, 4, 5, 2, 6]2.pop: 刪除單個或多個元素,按位刪除(根據索引刪除)iQ5少兒編程網-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> str.pop(1) #pop刪除時會返回被刪除的元素 >>> str [0, 2, 3, 4, 5, 6]>>> str2=['abc','bcd','dce'] >>> str2.pop(2) 'dce' >>> str2 ['abc', 'bcd']3.del:它是根據索引(元素所在位置)來刪除iQ5少兒編程網-https://www.pxcodes.com
舉例說明:iQ5少兒編程網-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還可以刪除指定范圍內的值。iQ5少兒編程網-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> del str[2:4] #刪除從第2個元素開始,到第4個為止的元素(但是不包括尾部元素) >>> str [0, 1, 4, 5, 6]del 也可以刪除整個數據對象(列表、集合等)iQ5少兒編程網-https://www.pxcodes.com
>>> str=[0,1,2,3,4,5,6] >>> del str >>> str #刪除后,找不到對象 Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> str NameError: name 'str' is not defined注意:del是刪除引用(變量)而不是刪除對象(數據),對象由自動垃圾回收機制(GC)刪除。iQ5少兒編程網-https://www.pxcodes.com
補充: 刪除元素的變相方法iQ5少兒編程網-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)相關推薦:Python3視頻教程
以上就是python中怎么刪除列表中的元素的詳細內容,更多請關注少兒編程網其它相關文章!iQ5少兒編程網-https://www.pxcodes.com

- 上一篇
python return用法是什么
簡介pythonreturn用法:1、返回函數的返回值;2、終止程序的運行,提前退出,例如,當函數內有錯誤發生時,使用return可以終止函數的運行。本教程操作環境:windows7系統、python3.9版,DELLG3電腦,該方法適用于所有品牌電腦。pythonreturn用法:(1)、返回函數的返
- 下一篇
python 怎么求平均值
簡介python求平均值的方法:首先新建一個python文件;然后初始化sum總和的值;接著循環輸入要計算平均數的數,并計算總和sum的值;最后利用“總和/數量”的公式計算出平均數即可。本文操作環境:Windows7系統,python3.5版本,DellG3電腦。首先我們先來了解一下計算平均數的IPO模