Python 使用索引列表从列表中弹出

Python 使用索引列表从列表中弹出,python,python-3.x,list,Python,Python 3.x,List,如何使用索引列表中的索引从列表1中弹出项目 list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171] index_list = [0,4,7,9,10] 使用列表。删除(项) 或list.pop(索引) 这里描述了这两种方法 在您的索引列表上使用(假设索引总是像您所展示的那样排序),因此您可以从列表的末尾删除项目,它应该可以正常工作 你可以试试这个- for n in reversed(index_list): list1.pop(n) pop

如何使用索引列表中的索引从列表1中弹出项目

list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
index_list = [0,4,7,9,10]
使用列表。删除(项)

或list.pop(索引)

这里描述了这两种方法

在您的索引列表上使用(假设索引总是像您所展示的那样排序),因此您可以从列表的末尾删除项目,它应该可以正常工作

你可以试试这个-

for n in reversed(index_list):
    list1.pop(n)

pop()
有一个可选的参数索引。它将删除索引中的元素

相反:保留那些不在列表中的元素:

for index in sorted(index_list, reverse=True):
    list1.pop(index)

print (list1)
注意:这不会修改现有列表,但会创建一个新列表

>>> list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
>>> index_list = [0,4,7,9,10]
>>> index_set = set(index_list) # optional but faster    
>>> [x for i, x in enumerate(list1) if i not in index_set]
[2, 5, 6, 8, 10, 69, 100, 105, 171]
结果

[2,5,6,8,10,69100105171]

enumerate将创建如下结构

list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
index_list = [0,4,7,9,10]


print([ t[1] for t in enumerate(list1) if t[0] not in index_list])

当然还原索引!注意:
列表。如果元素重复,删除
可能会失败。@tobias_\u k是的,你是对的。pop()是此处关于
print
语句的首选方法。在2.7环境下工作
>>> list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
>>> index_list = [0,4,7,9,10]
>>> index_set = set(index_list) # optional but faster    
>>> [x for i, x in enumerate(list1) if i not in index_set]
[2, 5, 6, 8, 10, 69, 100, 105, 171]
list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
index_list = [0,4,7,9,10]


print([ t[1] for t in enumerate(list1) if t[0] not in index_list])
[(0, 1), (1, 2),(2, 5),(3, 6),(4, 7),(5, 8),...(13, 171)]

Where t = (0,1) (index,item)
t[0] = index
t[1] = item