Python:根据条件从嵌套列表中移除子列表

2024-04-23 15:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个包含[1,1,0,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]]

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

有人能给我一个建议吗?提前谢谢!在


Tags: 列表建议
1条回答
网友
1楼 · 发布于 2024-04-23 15:14:22

您可以定义这样一个方法来确定给定的置换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))

然后阅读你的排列列表,如果它符合你的条件,就删除它。这是一个想法:

^{pr2}$

相关问题 更多 >