问题描述
如何从列表中删除在另一个列表中具有相应索引的所有元素?
a = [1,13,15,16,22,70,3]
index_list = [3,6]
因此最终列表应如下所示:
a = [1,70] # because we removed the elements that have their index equal to 3 and 6.
我尝试过此操作,但是由于删除导致列表的长度被修改,因此会破坏适当的删除:
i = 0
while i < len(a):
del a[index_list[i]]
i +=1
if (i < len(a)-1):
index_list[i+1] = index_list[i+1] - 1
我遇到一个错误。
我该如何进行这项工作?
解决方法
尝试
pip install -U virtualenv
,
result = [i for j,i in enumerate(a) if j not in index_list]
来自:Deleting multiple elements from a list,或以下pythonic:
result = []
for i,j in enumerate(a):
if j not in index_list:
result.add(i)
,
如果可以返回具有相同数据的新对象,请使用列表理解:
a = [val for j,val in enumerate(a) if j not in index_list]
但是,有时您可能希望就地修改原始对象。在这种情况下,您可以执行以下操作:
# get index list in reverse order
drop_inds = sorted(index_list,reverse=True)
# drop elements in-place
for idx in drop_inds:
del a[idx]
,
假设index_list的内容对a
的实际大小有效,那么从列表末尾到开头的删除就不会有问题:
a = [1,13,15,16,22,70,3]
index_list = [3,6]
for pos in reversed(index_list):
a.pop(pos)
print(f"{a=}")
将其变成功能更强大的一行,可以删除删除列表中的重复项并返回删除的内容:
a = [1,6,6]
print(f"before:{a=}")
removed = [a.pop(pos) for pos in reversed(list(set(index_list)))]
print(f"{removed=}")
print(f"after :{a=}")
输出:
before:a=[1,3]
removed=[3,16]
after :a=[1,70]
输出:
a=[1,70]
您甚至可以添加一些过滤条件,以删除不在a
长度范围内的索引。