从列表中查找连续数字的最长序列

时间:2018-06-01 09:15:52

标签: python-3.x

我想从列表中找到最大的连续数字序列。 我似乎无法在以下代码中找到问题。它没有返回正确的序列。

list1 = [2,5,1,2,3,4,5,6,15,13,20,21,22,30,32,35,36,37,38]

def finder(list1):

    lenlist = len(list1)
    p1 = 0 
    p2 = 1
    orglist = []
    templist = []

    while (p1 < lenlist-1 and p2 < lenlist-1):

        templist.append(list1[p1])

        while (p1 < lenlist-1 and p2 < lenlist-1):
            if(list1[p2] - list1[p1] == 1):
                templist.append(list1[p2])
                p1 += 1 
                p2 += 1
            else:
                p1 += 1
                p2 += 1
                break
        print('templist = ',templist)
        a = len(templist)
        b = len(orglist)

        if (b<a):
            orglist = templist
            print("orglist = ",orglist)
            templist[:] = []


        elif(b == a):       

            if (orglist[0]<templist[0]):
                orglist = templist
                print("orglist = ",orglist)
                templist[:] = []
            else:
                templist[:] = []

        else:
            print("orglist = ",orglist)
            templist[:] = []

    return(orglist)


running = finder(list1)

有人可以帮我在代码中找到问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用itertools.groupby简化代码,例如:

from itertools import groupby

list1 = [2,5,1,2,3,4,5,6,15,13,20,21,22,30,32,35,36,37,38]
grouped = ([el[1] for el in g] for k, g in groupby(enumerate(list1), lambda L: L[1] - L[0]))
res = max(grouped, key=len)
# [1, 2, 3, 4, 5, 6]