0

Assuming that I have a sorted list:

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

How can I get subsequence in a like:

[(1,2,3,4,5,6),(10,11,12,13,14,15,16),20,23,(25,26,27)]
Tardis Xu
  • 1,161
  • 2
  • 7
  • 9

1 Answers1

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)

output:

[(1, 2, 3, 4, 5, 6), (10, 11, 12, 13, 14, 15, 16), 20, 23, (25, 26, 27)]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111