简体   繁体   中英

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

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.

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 ).

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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