简体   繁体   English

如果嵌套列表包含某个值,则从列表中删除嵌套列表

[英]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.我有一个嵌套列表,我想删除空列表[]以及其中值为-1的任何嵌套列表。 Here is what I have so far, it was working earlier but I think jupyter was being buggy.这是我到目前为止所拥有的,它工作得更早,但我认为 jupyter 有问题。

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)?我的方法是否也有意义,或者是否有我忽略的更原生的解决方案(例如某种列表理解、lambda、过滤器等)?

You can simply use this list comprehension:您可以简单地使用此列表推导:

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

Output: 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))

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

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