Skip to main content
 首页 » 编程设计

python之在列表中查找连续数字的序列

2025年05月04日1598°冷暖

我有表单列表

[[143], [144, 210, 270], [145]] 

具有任意长度的任意数量的子列表。

我想构建一个函数来检查是否存在一系列连续(升序)数字,从每个列表中选取一个元素。序列的第一个元素应该在第一个列表中,第二个元素在第二个列表中,依此类推。如果序列存在,它应该返回序列。不需要找到每个可能的序列。如果序列不存在,则返回 'fail'。

例如,在上面的例子中,函数应该输出一个列表[143,144,145]。

我写了一个代码,但它只能部分工作。代码是

def pattern(example): 
    index = [0 for t in example] 
    stop = min([len(t) for t in example]) 
    i=0 
    while i < stop: 
        attempt = [0 for t in example] 
        j = 0 
        i+1 
        while j < len(example): 
            attempt[j] = example[j][index[i]] 
            try: 
                if example[j+1][index[j+1]] - example[j][index[j]] == 1: 
                    j+=1 
                    index[j]+=1 
                else: 
                    break 
            except: 
                break 
        if attempt[-1] != 0: 
            return attempt 
        else: 
            return 'fail' 

它只适用于 2 个子列表,我不明白为什么。有帮助吗?

请您参考如下方法:

您可以通过反复查找下一个 号码来大大简化您的代码in下一个列表。

def find( list_of_lists ): 
    for element in list_of_lists[0]: 
        start = element 
        next = element 
        for list in list_of_lists[1:]: 
            next+=1 
            print( "looking for {} in {}".format(next, list)) 
            if not next in list: 
                return 'fail' 
    return [x for x in range(start,next+1)] 
 
a = [[143], [144, 210, 270], [145]] 
 
find(a) 
looking for 144 in [144, 210, 270] 
looking for 145 in [145] 
 
[143, 144, 145] 
 

编辑:更正后的版本

def find( list_of_lists ): 
    num = len(list_of_lists) 
    for start in list_of_lists[0]: 
        try: 
            print( "starting with", start ) 
            next = start 
            last = start + num - 1 
            for list in list_of_lists[1:]: 
                next+=1 
                print( "looking for {} in {}".format(next, list)) 
                if not next in list: 
                    raise KeyError() 
                elif next == last: 
                    return [x for x in range(start,next+1)] 
          except KeyError: 
              pass 
    return 'fail' 
 
find(a) 
starting with 1 
looking for 2 in [3, 2, 6] 
looking for 3 in [5, 7, 4] 
starting with 3 
looking for 4 in [3, 2, 6] 
starting with 5 
looking for 6 in [3, 2, 6] 
looking for 7 in [5, 7, 4] 
 
[5, 6, 7]