简体   繁体   English

删除列表中的某些索引

[英]Remove certain indexes in a list

Suppose I have a list filled with indexes to remove 假设我有一个要删除的索引列表

remove = [0, 2, 4, 5, 7, 9, 10, 11]

Then I have another list of lists, such as 然后,我还有另一个列表列表,例如

l = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']]

I want to remove the values at the indexes in remove 我想删除remove中索引处的值

If you don't have to do this in place, you can construct new lists based on the index: 如果不必就地执行此操作,则可以根据索引构造新列表:

[[v for i, v in enumerate(s) if i not in to_remove] for s in l]
# [['b', 'd', 'g', 'i'], ['b', 'd', 'g', 'i']]

If you perform a step by step execution, the problem will become evident. 如果逐步执行,问题将变得很明显。

As you remove elements, the position of the following elements changes. 删除元素时,以下元素的位置会发生变化。 For example, if you remove element 0 from a list, what was element 1 will become element 0. 例如,如果从列表中删除元素0,则元素1原来是元素0。

If you want to stick with the current approach, just traverse the indices in reverse order (you don't need the values, just use a range ). 如果您想使用当前方法,只需以相反的顺序遍历索引(不需要值,只需使用range )。

If you don't want list comprehension, you can use a couple of loops like so: 如果您不希望列表理解,可以使用几个循环,如下所示:

for x in remove[::-1]:
    for list in l:
        del list[x]

[['b', 'd', 'g', 'i'], ['b', 'd', 'g', 'i']] [['b','d','g','i'],['b','d','g','i']

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

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