国产日韩欧美一区二区三区综合,日本黄色免费在线,国产精品麻豆欧美日韩ww,色综合狠狠操

極客小將

您現在的位置是:首頁 » python編程資訊

資訊內容

python中怎么刪除列表中的元素

極客小將2021-03-19-
簡介python刪除列表中元素的方法:1、使用remove()刪除單個元素,該函數可以刪除列表中某個值的第一個匹配項;2、使用pop()刪除單個或多個元素,該函數根據索引來刪除元素,并返回該元素的值;3、使用del關鍵字根據索引來刪除元素。本教程操作環境:windows7系統、python3版,DELL

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

>>> str=[1,2,3,4,5,2,6] >>> str.remove(2) >>> str

輸出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

預約試聽課

已有385人預約都是免費的,你也試試吧...

主站蜘蛛池模板: 旬阳县| 绥宁县| 东源县| 哈巴河县| 共和县| 弋阳县| 贺州市| 太保市| 河曲县| 汝城县| 武威市| 兴安盟| 阿巴嘎旗| 花莲市| 福泉市| 宜良县| 晋江市| 鄂托克前旗| 介休市| 梁平县| 阿鲁科尔沁旗| 永靖县| 湘乡市| 宜良县| 高台县| 酒泉市| 奉化市| 长丰县| 苍溪县| 耒阳市| 来凤县| 建德市| 鹤山市| 建德市| 瑞丽市| 汝州市| 德钦县| 包头市| 达孜县| 巴塘县| 高台县|