且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从列表中删除每次出现的子列表

更新时间:2023-12-04 20:31:28

您必须自己实现它.这是基本思想:

You'd have to implement it yourself. Here is the basic idea:

def remove_sublist(lst, sub):
    i = 0
    out = []
    while i < len(lst):
        if lst[i:i+len(sub)] == sub:
            i += len(sub)
        else:
            out.append(lst[i])
            i += 1
    return out

这将遍历原始列表的每个元素,并将其添加到输出列表(如果它不是子集的成员).这个版本的效率不是很高,但它的工作方式类似于您提供的字符串示例,因为它创建了一个不包含您的子集的新列表.只要它们支持==,它也适用于任意元素类型.从[1,1,1,1]中删除[1,1,1]会正确生成[1],就像字符串一样.

This steps along every element of the original list and adds it to an output list if it isn't a member of the subset. This version is not very efficient, but it works like the string example you provided, in the sense that it creates a new list not containing your subset. It also works for arbitrary element types as long as they support ==. Removing [1,1,1] from [1,1,1,1] will correctly result in [1], as for a string.

这是一个 IDEOne链接,展示了

>>> remove_sublist([1, 'a', int, 3, float, 'a', int, 5], ['a', int])
[1, 3, <class 'float'>, 5]