简体   繁体   English

Python:遵循标准从嵌套列表中删除子列表

[英]Python: Remove sublist from a nested list following a criterion

I'm trying to remove sublists from a nested list containing all the possible permutation of [1, 1, 1, 0, 0, 0, 0] 我试图从嵌套列表中删除 列表,其中包含[1,1,1,0,0,0,0]的所有可能的排列

[[0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 1], [1, 1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1], [0, 0, 1, 1, 0, 1, 0]]

I want to remove all the sublists in which there are 3 consecutive 0 or two couples of consecutive 0 (eg. i want to remove [1, 0, 1, 0, 0, 0, 1] or [0, 0, 1, 1, 0, 0, 1] ). 我想删除其中有3个连续0或2对连续0的所有子列表(例如,我想删除[1, 0, 1, 0, 0, 0, 1][0, 0, 1, 1, 0, 0, 1]

Can someone give me an advice on how to proceed? 有人可以就如何进行给我一个建议吗? Thanks in advance! 提前致谢!

You could define such a methode to find out if a given permutation p has those triple zeros or two double zeros : 您可以定义这样的方法,以确定给定的排列p是否具有那些三重零两个双零

def has_triple_zeros(p):
    for i, e in enumerate(p[:-2]):  # e are elements (0s and 1s) of the perm
        if e == 0:  # we encounter a 0
            if p[i+1] == 0 and p[i+2] == 0:  # the two following are also 0s
                return True
    return False  # we made it to the end, no triple 0s

def has_two_double_zeros(p):
    nb_doubles = 0
    i = 0  # init loop
    while i < len(p[:-1]):
        if p[i] == 0:  # we encounter a first 0
            if p[i+1] == 0:  # there is one next to it
                nb_doubles += 1
            i += 1  # skip the next element (already treated, cannot start new double)
        i += 1  # increment the loop
    return nb_doubles == 2


for p in lst:  # here, lst is your list of permutations
    print(p, has_two_double_zeros(p), has_triple_zeros(p))

Then just read your list of permutations and delete if it matches one of your criteria. 然后只需阅读您的排列列表,并删除它是否符合您的一个标准。 This is an idea: 这是一个想法:

res = list()  # result
for p in lst:
    if not (has_two_double_zeros(p) or has_triple_zeros(p)):
        res.append(p)

print(res)

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

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