使用python从列表中找到最长的连续子列表

时间:2017-02-20 13:18:37

标签: python-2.7

我有一个列表说[1,3,4,5,2,7,8,9,11,10,9,8,7,6,7,8],我们可以有[1,3,4,5],[7,8,9,11], [11,10,9,8,7,6]这样的序列,所以我需要写一个逻辑来找到最长的子列表序列(例子中的最后一个)。列表将是正整数,但可以是任何顺序(asc,desc)。

好的,这是我尝试查找升序顺序,可能正在运行:

l = [1,3,4,3,2,1,7,8,9,11,12,12,8,7,6,7,8]
ll = []
temp = l[0]
ll.append(l[0])
keyval = {}

for x in range(1,len(l)):
    #print (str(x)+ "  :"+str(l[x]))
    if l[x] >= temp :
      ll.append(l[x])
      temp = l[x]
      #print (ll)
    else:
      keyval[len(ll)] = ll
      ll=[]
      temp = l[x]

max_key = max(keyval.keys())
print (keyval[max_key])

输出为:[7,8,9,11,12,12]

但我没有找到逻辑来集成desc顺序序列。请帮忙

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案(虽然非常丑陋:-):

def longest_consecutive(values, elem):
    global long
    if not values or values[-1] + 1 == elem:
        values.append(elem)
        if len(values) > len(long):
            long = values[:]  # shallow copy
    else:
        values = []
    return values

example = [1, 3, 4, 5, 2, 7, 8, 9, 11, 10, 9, 8, 7, 6, 7, 8]
long = []  # modified by reducing function
longest = []
reduce(longest_consecutive, example, [])
longest.append(long)
reduce(longest_consecutive, example[::-1], [])  # [::-1] means reverse order
longest.append(long[::-1])  # result must be reversed too
print(max(longest))