简体   繁体   中英

remove a list of lists while iterating over it

I know that you are not supposed to remove an element of a list while iterating over it but I have to. I'm trying to iterate over a list of lists and if I find a value in a list of my lists i need to remove it. This is what I've tried so far.

dict[["A1","A2"],
     ["B1","B2"],
     ["C1","C2"]]

for i in range(len(dict)):
    if dict[i][0]=="A1":
        dict.pop(i)

But it's giving me an error of out of range. How can I do it with list comprehensions or any other approach?

Do you mean this?

old = [["A1","A2"], ["B1","B2"], ["C1","C2"]]
new = [x for x in old if x[0] != "A1"]

You can't. You will get an exception. Create a new list as a copy.

>>> disallowed = [1, 2, 3]
>>> my_list = [ [1, 2, 3, 4, 5, 6, 7], [3, 3, 4, 5, 8, 8, 2] ]
>>> filtered_list = [[y for y in x if y not in disallowed] for x in my_list]
>>> print filtered_list
[[4, 5, 6, 7], [4, 5, 8, 8]]

You can actually delete from a list while you iterate over it, provided you to it backwards (so deletion only affects higher indices which you have already seen during this iteration):

data = [["A1","A2"],
        ["B1","B2"],
        ["C1","C2"]]

for i, pair in reversed(data):
    if pair[0] == 'A1':
        del data[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