如何按顺序检查一个列表是否是另一个列表的子序列

2024-09-29 22:10:37 发布

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

我有一个清单input

[1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 2, 7, 1, 7, 2, 1]

我需要检查alookup_list{}的元素是否以相同的顺序分散在上面的列表中

这将说明我想说的:

“强<<<强>1<<强<<强<<强>1<强<<强<<强<<强<<强>1<强<<强>3<强<<强>3<强<<强<<强<<强<<强<<强<<强<<强<<强>1<强<<强<<强<<强>1<强<<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强>3<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强<<强<<强>3<强<<强<<强<<强<<强<<强<4,9,3,4,8,4,8,5,3,5,4,7,3,7,3,1,2,7,1,7,2,1]

粗体数字是lookup_list列表中相同顺序中出现的lookup_list中的数字,但中间还有其他不相关的项目

我能查一下这个吗

这是我尝试过的方法:

count = 0
a = 0
indices = []
for item in list:
    idx = -1
    if count < len(input_list):
        idx = list.index(input_list[count])
        if idx != -1:
            a = a +len(list[:idx])
            list = list[idx:]
            indices.append(a + idx)
    count = count +1
print(indices)

但它给了我以下结果:

[0, 2, 5, 35, 25, 24, 33, 30, 33, 37, 38, 64, 54]

问题是,在这个方法中lookup_list的顺序没有得到维护


Tags: 项目方法元素列表inputlenif顺序
3条回答
def check_exists(l, lookup_list):
check = True
for i in lookup_list:
    try:
        index = l.index(i) 
        l = l[index+1:]
    except ValueError:
        check = False 
        break 
return check

check_exists()函数将接受完整列表和查找列表作为参数,如果序列存在,则返回True;如果序列不存在,则返回false

以下是完整的程序-

def check_exists(l, lookup_list):
    check = True
    for i in lookup_list:
        try:
            index = l.index(i) 
            l = l[index+1:]
        except ValueError:
            check = False 
            break 
    return check



l = [1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 
4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 
2, 7, 1, 7, 2, 1]
lookup_list = [2,3,4,5,7,8,9,5,4,3,2,1] 

print(check_exists(l,lookup_list))

您可以在输入列表上使用迭代器。调用next获取每个值。如果在没有找到所有匹配项的情况下耗尽迭代器,将得到一个StopIteration,然后返回False

def check(input_, lookup_list):
    it = iter(input_)
    try:
        for i in lookup_list:
            # read values from the input list until we find one which 
            # matches the current value from the lookup list
            while next(it) != i: 
                pass
        # we found matches for everything on the lookup list
        return True
    except StopIteration:
        # we tried to go past the end of the input list
        return False

最简单的方法是将第一个列表(不要称之为input!)转换为字符串(尖括号将多个数字“放在一起”):

input_str = "".join("<"+str(i)+">" for i in input_list)

将第二个列表转换为正则表达式,该正则表达式允许在所需项之间添加可选的附加项:

lookup_str = ".*" + ".+".join("<"+str(i)+">" for i in lookup_list) + ".+"

现在,检查输入字符串是否与正则表达式匹配:

if (re.search(lookup_str, input_str)): # there is a match

相关问题 更多 >

    热门问题