在 Python 中删除范围内的元素


直接使用元素的索引和 del 函数从 python 中删除单个元素非常简单。但有时我们可能需要在组索引中删除元素。本文探讨了仅从列表中删除指定在索引列表中的那些元素的方法。

使用 sort 和 del

在此方法中,我们创建一个包含要删除的索引值的列表。我们对其进行排序并逆序,以保留列表元素的原始顺序。最后,我们对那些特定索引位置的原始给定列表应用 del 函数。

示例

 实际演示

Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]

# Print result
print("List after deleted elements : " ,Alist)

输出

运行上面的代码,会得到以下结果 −

Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]

排序并逆序后的 idx_list 变成了 [0,1,3]。因此,仅从这些位置删除元素。

使用 enumerate 和 not in

我们还可以在 for 循环中,通过使用 enumerate 和 not in 子句来编写上面的程序。结果与上述相同。

示例

 实际演示

Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]

# Print result
print("List after deleted elements : " ,Alist)

输出

运行上面的代码,会得到以下结果 −

Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]

更新时间:04-05-2020

733 人查看

开启您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.