Python程序使用列表推导从列表中删除多个元素
我们可以使用以下语法从列表中的多个索引中删除元素,
indices = index1, index2, ...
list_name = [i for j, i in enumerate(list_name) if j not in indices]在这里,我们正在实现一个python程序,以使用listcomprehension从列表中删除多个元素。
示例
Input:
list1 = [10, 20, 30, 40, 50, 60, 70]
indices = 0, 2, 4
Output:
list1 = [20, 40, 60, 70]
Input:
list1 = [10, 20, 30, 40, 50, 60, 70]
indices = 1, 3
Output:
list1 = [10, 30, 50, 60, 70]程序:
#Python程序删除多个元素
#从列表中使用列表理解
list1 = [10, 20, 30, 40, 50, 60, 70]
#打印列表
print("The list is: ")
print(list1)
#列出理解,删除元素
indices = 0, 2, 4
list1 = [i for j, i in enumerate(list1) if j not in indices]
#打印列表 after removeing elements
print("After removing elements, list is: ")
print(list1)输出结果
The list is: [10, 20, 30, 40, 50, 60, 70] After removing elements, list is: [20, 40, 60, 70]