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

时间:2017-03-30 13:03:36

标签: python python-2.7

我正在尝试从嵌套列表中删除子列表,其中包含[1,1,1,0,0,0,0]的所有可能的排列< / p>

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

我想删除其中有3个连续0或2对连续0的所有子列表(例如,我想删除[1, 0, 1, 0, 0, 0, 1][0, 0, 1, 1, 0, 0, 1])。

有人可以就如何继续提供建议吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以定义这样的方法,以确定给定的排列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))

然后只需阅读您的排列列表,如果符合您的某个条件,请将其删除。这是一个想法:

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

print(res)