我如何检查一个列表是否以相同的顺序在另一个列表中?

How would I check if a list is in another list in the same order?

基本上,对于一项作业,我需要确定一个列表是否是另一个列表的子列表,我在 post , however there are some special requirements, that will be explained in the examples, that werent answered in that post. I also saw this post 中看到了答案,这也无助于确定特殊要求。

示例 1:

list1 = 'a,q,b,q,q,q,q,q,q,c'
sublist = 'a,b,c'
output -> True

解释:现在,我知道这不一定是 list1 的子列表,但是 a、b 和 c 都存在于 list1 中,与子列表变量的顺序相同,只有 q 分隔它们,我可以忽略,因为 q 不在子列表中,这就是输出 true 的原因。

示例 2:

list1 = 'b,q,q,q,q,a,q,c'
sublist = 'a,b,c'
output -> False

解释:虽然这个列表确实像另一个例子一样包含 a、b 和 c,但它是乱序的,因此它是错误的

示例 3:

list1 = 'a,b,b,q,c'
sublist = 'a,b,c'
output -> False

示例 4:

list1 = 'a,b,b,a,b,q,c'
sublist = 'a,b,c'
output -> True

解释:在列表的开头我们有 a、b、b,在之前的解释中我说的是错误的,但是在该部分之后我们有正确的顺序 a、b、c,其中 a q 分隔 b和 c

这是我的代码。我似乎无法找到的问题出现在一个隐藏的测试用例中,我必须 运行 通过,我看不到输入或输出,这使得调试变得困难。我已经尝试 运行 许多我自己的不同测试用例,但我似乎无法找到我在这里缺少的东西。我只是想知道是否有人能弄清楚我在 运行 执行此操作时忘记考虑的内容。

sublist = 'a,b,c'.split(',')
l1 = 'a,q,b,a,q,q,q,q,q,q,q,q,q,c'.split(',')
item_order = []

for item in l1:
    #Check if I have found a sublist
    if item_order == sublist:
        break

    #If item is in sublist, but hasnt been seen yet
    elif item in sublist and item not in item_order:
        item_order.append(item)
        print('adding item', item_order)

    #If item has been seen and is in sublist
    elif item in item_order:
        #Reset and add duplicated item 
        item_order = []
        item_order.append(item)
        print('found duplicate, resetting list', item_order)

if item_order == sublist: print("true")
else: print("false")

可以过滤list1中不存在于sublist中的元素,与sublist进行比较,即:

def good_seq(list1, sublist):
    return [x for x in list1.split(",") if x in sublist.split(",")] == sublist.split(",")

Demo

你可以尝试以下方法吗:

def dedupe(items):
    """Function to remove duplicate by preserving its order

    Args:
        items (list): the list  for which the duplicates must be removed

    Yields:
        generator: the generator with unique items
    """
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

def check_order(l1, sublist):
    l1 = list(dedupe(l1))
    result = [val for val in l1 if val in sublist] == sublist
    return result

sublist = 'a,b,c'.split(',')
l1 = 'a,q,b,a,q,q,q,q,q,q,q,q,q,c'.split(',')
print(check_order(l1, sublist))

sublist = 'a,b,c'.split(',')
l1 = 'b,q,q,q,q,a,q,c'.split(',')
print(check_order(l1, sublist))

输出:

True
False