-1

I have this list nums=[1,2,6,7,8,9,44,90,110,111,112]

I want to divide them into sub lists based on sequence

44 : there is no number before and after ;Excluded

90 same as 44

so the final output will be

finall_lst=[[1,2],[6,7,8,9],[110,111,112]]

I want that list to be dynamic so that it can receive any number of items even millions

thanks

paull
  • 15
  • 2
  • 7
  • What have you tried so far? What results did you get? This looks like a school assignment, and Stack Overflow is not meant for other people to solve your problem, but rather to help you when you get stuck – ibarrond Jun 26 '20 at 12:03
  • You could use one of the solutions in the duplicate and then filter the list based on the sublist length being greater than 1 – Nick Jun 26 '20 at 12:05
  • I thought that I do for loop for each item and at that item I thought to define variable which will plus 1 and if that equals it will append to another list and finally but It is hard to do in a code – paull Jun 26 '20 at 12:06

1 Answers1

0

Here's the solution to find group sequence from the list.

def groupSequence(x): 
    it = iter(x)
    prev, res = next(it), []
    
    while prev is not None:
        start = next(it, None)
        if prev + 1 == start:
            res.append(prev)
        elif res:
            yield list(res + [prev])
            res = [] 
        prev = start 

        
nums=[1,2,6,7,8,9,44,90,110,111,112]
print(list(groupSequence(nums))) 
Umer Rana
  • 148
  • 6
  • I got an answer ... based on the question which referred up in another page... I will try it when Iam free ... thanks for posting an answer ❤❤ – paull Jun 26 '20 at 12:40