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