简体   繁体   中英

Remove nested lists from a list if nested list contains a certain value

I have a nested list and I would like to remove the empty list [] and any nested list that has a value of -1 in it. Here is what I have so far, it was working earlier but I think jupyter was being buggy.

regions = [[], [2, -1, 1], [4, -1, 1, 3], [5, 0, -1, 4], [9, 10, 7, 8], 
                    [7, 6, 10], [8, 0, 5, 6, 7], [9, 2, 1, 3, 10], 
                    [9, 2, -1, 0, 8], [10, 3, 4, 5, 6]]

counter = range(len(regions))
for region in counter:
    print(region)
    for i in range(len(regions[region])): # IndexError: list index out of range
    #print(regions[region])
        if regions[region][i] == -1:
            regions.remove(regions[region])
            break
print(regions)

I think the issue is when I am removing a region from the regions list, the counter for the regions nested list is modified and that makes me run out of index values before I finish iterating through each nested list.

Also does my approach even make sense or is there a more native solution that I am overlooking (such as some sort of list comprehension, lambda, filter, etc)?

You can simply use this list comprehension:

regions = [i for i in regions if i and (-1 not in i)]

Output:

[[9, 10, 7, 8], [7, 6, 10], [8, 0, 5, 6, 7], [9, 2, 1, 3, 10], [10, 3, 4, 5, 6]]

you can also use:

regions = list(filter(lambda r: r and (r.count(-1)==0),regions))

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