Python程式:移除陣列/列表中所有指定元素
陣列是由儲存在連續記憶體位置的同類型元素組成的集合。Python本身並不支援內建陣列。如果您需要使用陣列,則需要匯入“array”模組或使用numpy庫中的陣列。
在Python中,我們可以使用列表代替陣列。但是,我們無法限制列表的元素必須是相同的資料型別。
給定的任務是從陣列/列表中移除所有指定元素的出現,即移除包括重複元素在內的指定元素。讓我們透過一個輸入輸出場景來了解這是如何工作的。
輸入輸出場景
考慮一個包含一個或多個重複元素(重複元素)的列表。
my_list = [ 1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10 ].
現在,假設我們需要移除元素10。我們可以清楚地看到元素10在列表中存在,並且重複了5次。移除所有出現後,生成的列表將如下所示:
my_list = [ 1, 20, 21, 16, 18, 22, 8 ].從Python列表中移除元素的方法有很多種。讓我們逐一討論它們。
使用remove()方法
Python中的remove()方法接受單個值作為引數,該值代表列表的元素,並將其從當前列表中移除。為了使用此方法移除所有出現,我們需要將所需元素與列表中的所有其他元素進行比較,並且每當發生匹配時,都需要呼叫remove()方法。
示例
在這個例子中,我們將建立一個元素列表,並使用remove()方法移除所有值為10的元素。
def removing_elements(my_list, element):
element_count = my_list.count(element)
for i in range(element_count):
my_list.remove(element)
return my_list
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
輸出
上述程式的輸出如下:
The list before performing the removal operation is: [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10] The list after performing the removal operation is: [1, 20, 21, 16, 18, 22, 8]
使用列表推導式
“列表推導式”技術由冗長的單行語句組成,可以完成整個任務。使用它可以構造一個新的列表,只要滿足給定的基本條件,就可以儲存其餘元素。
在這裡,我們搜尋所需的元素,找到後,我們構造另一個列表,使得匹配的元素被排除,即除了匹配的元素外,所有其他元素都將儲存在新構造的列表中,該列表最終被視為結果列表。
示例
讓我們看一個例子:
def removing_elements(my_list, element):
result = [i for i in my_list if i != element]
return result
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
輸出
上述程式的輸出如下:
The list before performing the removal operation is: [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10] The list after performing the removal operation is: [1, 20, 21, 16, 18, 22, 8]
使用“filter()”方法
filter()方法接受一個函式和一個可迭代物件作為引數,並根據函式描述的條件過濾給定可迭代物件的元素。
在這裡,使用filter()和__ne__(不等於運算子的功能)方法,我們可以過濾列表中不等於所需元素的元素。
示例
在這個例子中,我們使用filter()方法移除列表中所有特定元素的出現。
def removing_elements(my_list, element):
result = list(filter((element).__ne__, my_list))
return result
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
輸出
上述程式的輸出如下:
The list before performing the removal operation is: [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10] The list after performing the removal operation is: [1, 20, 21, 16, 18, 22, 8]
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP