0

假设我有一个排序列表:

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)]
4

1 回答 1

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)]
于 2015-07-29T12:03:29.773 回答