list常用函式和方法續之刪除元素

2021-08-21 17:27:32 字數 1752 閱讀 3204

month=['january','february','march','april','may','june','july','august','september','october','november','december','none']包含了乙個與其他元素格格不入的元素"none",為了讓month只包含月份的字串,需要把元素「none」從列表物件中刪除,具體方法如下所述:

(1)使用del語句刪除列表元素

在python中,使用del語句可將物件刪除,實質上del語句是賦值語句(=)的逆過程,若把賦值語句看作是「向物件帖變數名標籤」,則del語句就是「將物件上的標籤撕下來」,即將乙個物件與它的變數名進行分離操作。使用del語句可將列表中提取出來的元素刪除,**如下所示:

month = ['january','faburary','march','april','may','june','july','august','september','october','november','december','none']

month_copy = month.copy()#建立乙個列表物件month副本

del month_copy[-1] #刪除副本中最後乙個元素

(2)使用pop語句刪除列表元素

利用元素位置可以對元素進行刪除操作。將元素索引傳入pop語句中,將會獲取該元素,並將其在列表中刪除,相當於把列表中元素抽離出來。若不能指定元素位置,pop語句將預設使用索引-1,**如下所示:

month=['january','feburary','march','april','may','june','july','august','september','october','november','december']

month_copy=month.copy() #建立乙個列表物件month副本

print(month_copy)#檢視 month 副本

#獲取並刪除第4個元素

print(month_copy.pop(3)) #檢視第4個元素

del_element=month_copy.pop()#將最後乙個元素賦值給乙個變數並在副本中刪除

print(del_element) #檢視刪除元素

print(month_copy) #檢視month副本

(3) 使用remove語句刪除列表元素

除了利用元素位置進行元素刪除外,還可以將指定元素進行刪除。將指定元素傳入remove語句,則列表中第一次出現的該元素會被刪除,**如下所示:

month=['january','feburary','march','april','may','june','july','august','semptember','october','november','december','none']

#檢視原始列表元素

print(month)

month.remove('none') #刪除列表中的元素『none』

print(month)# 檢視刪除後的列表元素

常用函式和方法集

1 datetime 數字型 system.datetime currenttime new system.datetime 1.1 取當前年月日時分秒 currenttime system.datetime.now 1.2 取當前年 int 年 currenttime.year 1.3 取當前月 ...

jQuery常用方法和函式

bind 方法 被選元素新增乙個或多個事件處理程式,並規定事件發生時執行的函式 selector bind button bind click function focus data fn 元素獲得焦點時,觸發 focus 事件 input type text focus function 無法使用...

C 常用函式和方法集

1 datetime 數字型 system.datetime currenttime new system.datetime 1.1 取當前年月日時分秒 currenttime system.datetime.now 1.2 取當前年 int 年 currenttime.year 1.3 取當前月 ...