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 #Python學習交流群:778463939
[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 #Python學習交流群:778463939
[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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/171252.html
標籤:其他
