在python中收集列表中的序列

时间:2015-07-29 11:55:36

标签: python search sequence subsequence

假设我有一个排序列表:

a=[1,2,3,4,5,6,10,11,12,13,14,15,16,20,23,25,26,27]

如何在a中得到子序列,如:

[(1,2,3,4,5,6),(10,11,12,13,14,15,16),20,23,(25,26,27)]

1 个答案:

答案 0 :(得分:0)

a=[1,2,3,4,5,6,10,11,12,13,14,15,16,20,23,25,26,27]

lst = []
last = None

for item in a:
    if last is None:
        current = [item]
    elif item - last == 1:
        current.append(item)
    else:
        if 1 == len(current):
            lst.append(current[0])
        else:
            lst.append(tuple(current))
        current = [item]
    last = item
lst.append(tuple(current))

print(lst)

输出:

[(1, 2, 3, 4, 5, 6), (10, 11, 12, 13, 14, 15, 16), 20, 23, (25, 26, 27)]