Python程式:移除列表中第n次出現的指定單詞(單詞可能重複)
當需要從一個單詞列表中移除特定出現次數的指定單詞時(單詞可能重複),可以定義一個方法,該方法迭代列表,並將計數器加1。如果計數器與指定的出現次數匹配,則可以刪除列表中的特定元素。
下面是一個演示:
示例
def remove_word(my_list, my_word, N):
count = 0
for i in range(0, len(my_list)):
if (my_list[i] == my_word):
count = count + 1
if(count == N):
del(my_list[i])
return True
return False
my_list = ['Harry', 'Jane', 'Will', 'Rob', 'Harry']
print("The list is :")
print(my_list)
my_word = 'Harry'
N = 2
flag_val = remove_word(my_list, my_word, N)
if (flag_val == True):
print("The updated list is: ", my_list)
else:
print("Item hasn't been updated")輸出
The list is : ['Harry', 'Jane', 'Will', 'Rob', 'Harry'] The updated list is: ['Harry', 'Jane', 'Will', 'Rob']
解釋
定義了一個名為“remove_word”的方法,該方法將列表、一個單詞和“n”的值作為引數。
將“count”值初始化為0。
迭代列表,並檢查列表中的元素是否與指定單詞匹配。
如果匹配,則將count變數加1。
如果此count變數等於值“n”,則從列表中刪除該元素。
使用“del”關鍵字。
定義一個字串列表並在控制檯中顯示。
透過傳遞相關引數來呼叫該方法。
在控制檯中顯示輸出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP