且构网

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

确定列表中的所有元素是否都存在并且在另一个列表中是否以相同的顺序出现

更新时间:2023-11-28 16:37:52

这是使用迭代器在线性时间(和恒定空间)中进行操作的一种方法:

Here's one way to do it in linear time (and constant space) with an iterator:

def sublist(a, b):
    seq = iter(b)
    try:
        for x in a:
            while next(seq) != x: pass
        else:
            return True
    except StopIteration:
        pass
    return False

基本上,它遍历子列表的每个元素,并查看是否可以在尚未查看的完整列表的一部分中找到相同的元素.如果它遍历整个子列表,则意味着我们有一个匹配项(因此for循环上的else语句).如果我们没有足够的元素来查看完整列表,则意味着我们没有匹配项.

Basically it goes through each element of the sublist, and sees if it can find that same element in the part of the complete list it hasn't looked at yet. If it makes it through the entire sublist it means we have a match (hence the else statement on the for loop). If we run out of elements to look at in the complete list, it means we don't have a match.

我已经更新了解决方案,使其可以在Python 3中使用.对于Python 2.5和更早的版本,next(seq)需要替换为seq.next().

I have updated my solution so it works with Python 3. For Python 2.5 and older, next(seq) needs to be replaced with seq.next().