简体   繁体   English

如何遍历列表以删除项目索引?

[英]How to iterate over a list to remove index of item?

I have 2 lists: 我有2个清单:

l1=[(1,2),(3,4),(5,6)]
l2 = [0,2]

L2 contains a list of indexes. L2包含索引列表。 I want to delete the index of the element in l1 that correspond to the index in l2. 我想删除l1中与l2中的索引相对应的元素的索引。

How can that be done? 那怎么办?

for i in l2:
    l2.pop(i)

Doesn't work because the index changes after popping the first one. 不起作用,因为在弹出第一个索引后索引会更改。

I saw this answer somewhere but its not working by deleteing indexes: 我在某处看到了此答案,但通过删除索引无法正常工作:

somelist = [x for x in somelist if not determine(x)]
l2 = set(l2)   # for speedy lookups
l1 = [x for i, x in enumerate(l1) if i not in l2]

您始终可以先对索引列表进行排序,然后反向进行索引遍历,以确保删除正确的值

for i in sorted(l2)[::-1]: l1.pop(i)

You could go in reverse order to avoid that problem: 您可以按照相反的顺序来避免该问题:

l1 = [(1, 2), (3, 4), (5, 6)]
l2 = [0, 2]

for i in reversed(l2):
    del l1[i]
print l1 # [(3, 4)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM