Python 程式刪除列表中的索引元素
如果需要刪除列表中索引處的元素,可以使用“enumerate”屬性、“not in”運算子、一個簡單迭代和“append”方法。
示例
以下對其進行了演示:
my_list = [91, 75, 15, 45, 69, 78, 23, 71, 36, 72]
print("The list is : " )
print(my_list)
print("The list after sorting is : " )
my_list.sort()
print(my_list)
index_list = [2, 4, 5, 7]
print("The index values stored in the list are :")
print(index_list)
my_result = []
for index, element in enumerate(my_list):
if index not in index_list:
my_result.append(element)
print("The resultant list is : ")
print(my_result)
print("The list after sorting is : " )
my_result.sort()
print(my_result)輸出
The list is : [91, 75, 15, 45, 69, 78, 23, 71, 36, 72] The list after sorting is : [15, 23, 36, 45, 69, 71, 72, 75, 78, 91] The index values stored in the list are : [2, 4, 5, 7] The resultant list is : [15, 23, 45, 72, 78, 91] The list after sorting is : [15, 23, 45, 72, 78, 91]
說明
定義了一個列表並顯示在控制檯上。
對其進行排序並顯示在控制檯上。
索引值儲存在一個列表中。
它們也顯示在控制檯上。
建立一個空列表。
對列表進行迭代,並設定一個“if”條件。
這用於檢查索引是否不在索引值列表中。
如果不是,則將該元素追加到空列表。
這顯示為控制檯上的輸出。
再次對列表進行排序並顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP