Python – 删除列表中索引处的元素
给定列表,删除索引列表中存在的所有元素。
Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5]
Output : [5, 6, 7, 2, 10]
Explanation : 3, 6, and 1 has been removed.
Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2]
Output : [5, 6, 7, 8, 1, 2, 10]
Explanation : 3 has been removed.
方法 #1:使用 enumerate() + 循环
在此,我们迭代所有元素,如果索引存在于列表中,则该索引元素从结果列表中省略。
Python3
# Python3 code to demonstrate working of
# Remove elements at Indices in List
# Using loop
# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing idx list
idx_list = [2, 4, 5, 7]
res = []
for idx, ele in enumerate(test_list):
# checking if element not present in index list
if idx not in idx_list:
res.append(ele)
# printing results
print("Filtered List after removal : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove elements at Indices in List
# Using enumerate() + list comprehension
# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing idx list
idx_list = [2, 4, 5, 7]
# one-liner to test for element in index list
res = [ele for idx, ele in enumerate(test_list) if idx not in idx_list]
# printing results
print("Filtered List after removal : " + str(res))
输出
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
方法 #2:使用 enumerate() + 列表推导
在此,我们以紧凑的方式使用列表推导执行迭代任务,其余方法与上述类似。
Python3
# Python3 code to demonstrate working of
# Remove elements at Indices in List
# Using enumerate() + list comprehension
# initializing list
test_list = [5, 6, 3, 7, 8, 1, 2, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing idx list
idx_list = [2, 4, 5, 7]
# one-liner to test for element in index list
res = [ele for idx, ele in enumerate(test_list) if idx not in idx_list]
# printing results
print("Filtered List after removal : " + str(res))
输出
The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]