自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python教程:刪除列表中某個(gè)元素的三種方法

開發(fā) 后端
python中關(guān)于刪除list中的某個(gè)元素,一般有三種方法:remove、pop、del 。

python中關(guān)于刪除list中的某個(gè)元素,一般有三種方法:remove、pop、del:

1.remove: 刪除單個(gè)元素,刪除首個(gè)符合條件的元素,按值刪除

舉例說明:

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

2.pop: 刪除單個(gè)或多個(gè)元素,按位刪除(根據(jù)索引刪除)

>>> 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ù)索引(元素所在位置)來刪除

舉例說明:

>>> str=[1,2,3,4,5,2,6]
>>> str2.pop(2)
[1, 3, 4, 5, 2, 6]
>>> str2=['abc','bcd','dce']
>>> del str2[1]
>>> str2
['abc', 'dce']

除此之外,del還可以刪除指定范圍內(nèi)的值。

#Python學(xué)習(xí)交流QQ群:778463939
>>> str=[0,1,2,3,4,5,6]
>>> del str[2:4] #刪除從第2個(gè)元素開始,到第4個(gè)為止的元素(但是不包括尾部元素)
>>> str
[0, 1, 4, 5, 6]

del 也可以刪除整個(gè)數(shù)據(jù)對(duì)象(列表、集合等)

>>> 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)刪除。

補(bǔ)充: 刪除元素的變相方法

print('s1_2:', s1)
's3:', s3)
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 = s3
print('s2:', s2)
print('s3:', s3)
print('s1_2:', s1)


責(zé)任編輯:龐桂玉 來源: 馬哥Linux運(yùn)維
相關(guān)推薦

2021-02-03 18:05:30

Python方法列表

2021-02-06 11:26:55

Python開發(fā)list

2022-07-13 16:06:16

Python參數(shù)代碼

2024-11-15 07:00:00

Python發(fā)送郵件

2010-11-10 13:28:06

SQL Server刪

2010-09-08 13:29:48

CSS

2022-10-28 11:07:03

2021-12-20 07:11:26

Java List排序 Java 基礎(chǔ)

2009-07-08 12:56:32

編寫Servlet

2022-05-31 16:00:46

Go 編程語(yǔ)言復(fù)制文件Go 標(biāo)準(zhǔn)庫(kù)

2011-06-10 10:43:12

Ubuntu應(yīng)用安裝

2009-06-23 10:45:18

Hibernate支持

2022-03-26 09:18:06

Linux命令行工具刪除文件

2022-04-28 07:26:17

PythonDocker容器

2009-12-11 18:49:39

預(yù)算編制博科資訊

2011-04-18 15:32:45

游戲測(cè)試測(cè)試方法軟件測(cè)試

2010-09-14 15:10:49

CSS注釋

2023-08-14 17:58:13

RequestHTTP請(qǐng)求

2011-07-25 10:58:29

服務(wù)器

2015-08-04 09:18:26

JavaArrayList元素
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)