python中關於刪除list中的某個元素,通常有三種方法:remove、pop、del:python
1.remove: 刪除單個元素,刪除首個符合條件的元素,按值刪除
舉例說明:shell
>>> str=[1,2,3,4,5,2,6] >>> str.remove(2) >>> str
[1, 3, 4, 5, 2, 6]app
2.pop: 刪除單個或多個元素,按位刪除(根據索引刪除)ide
>>> 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:它是根據索引(元素所在位置)來刪除
舉例說明:rem
>>> str=[1,2,3,4,5,2,6] >>> del str[1] >>> str
[1, 3, 4, 5, 2, 6]it
>>> str2=['abc','bcd','dce'] >>> del str2[1] >>> str2
['abc', 'dce']ast
除此以外,del還能夠刪除指定範圍內的值。class
>>> str=[0,1,2,3,4,5,6] >>> del str[2:4] #刪除從第2個元素開始,到第4個爲止的元素(可是不包括尾部元素) >>> str
[0, 1, 4, 5, 6]
del 也能夠刪除整個數據對象(列表、集合等)
>>> 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)刪除。
補充: 刪除元素的變相方法
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)
python中關於刪除list中的某個元素,通常有三種方法:remove、pop、del:
1.remove: 刪除單個元素,刪除首個符合條件的元素,按值刪除
舉例說明:
>>> str=[1,2,3,4,5,2,6] >>> str.remove(2) >>> str
[1, 3, 4, 5, 2, 6]
2.pop: 刪除單個或多個元素,按位刪除(根據索引刪除)
>>> 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:它是根據索引(元素所在位置)來刪除
舉例說明:
>>> 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還能夠刪除指定範圍內的值。
>>> str=[0,1,2,3,4,5,6] >>> del str[2:4] #刪除從第2個元素開始,到第4個爲止的元素(可是不包括尾部元素) >>> str
[0, 1, 4, 5, 6]
del 也能夠刪除整個數據對象(列表、集合等)
>>> 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)刪除。
補充: 刪除元素的變相方法