Group Consecutive Increasing Numbers in List

Viewed 513

How can I group together consecutive increasing integers in a list? For example, I have the following list of integers:

numbers = [0, 5, 8, 3, 4, 6, 1]

I would like to group elements together as follow:

[[0, 5, 8], [3, 4, 6], [1]]

While the next integer is more than previous, keep adding to the same nested list; ones the next integer is smaller, add nested list to main list and start again.

I have tried few different ways (while loop, for loop, enumerate and range), but cannot figure out how to make it append to the same nested list as long as next integer is larger.

result = []

while (len(numbers) - 1) != 0:
    group = []

    first = numbers.pop(0)
    second = numbers[0]

    while first < second:
        group.append(first)
        
        if first > second:
            result.append(group)
        break
3 Answers

You could use a for loop:

numbers = [0, 5, 8, 3, 4, 6, 1]
result = [[]]
last_num = numbers[0] # last number (to check if the next number is greater or equal)
for number in numbers:
    if number < last_num:
        result.append([]) # add a new consecutive list
    result[-1].append(number) 
    last_num = number # set last_num to this number, so it can be used later
print(result)

NOTE: This doesn't use .pop(), so the numbers list stays intact. Also, one loop = O(N) time complexity!!

If pandas are allowed, I would do this:

import pandas as pd
numbers = [0, 5, 8, 3, 4, 6, 1]
df = pd.DataFrame({'n':numbers})
[ g['n'].values.tolist() for _,g in df.groupby((df['n'].diff()<0).cumsum())]

produces

[[0, 5, 8], [3, 4, 6], [1]]

You can do this:

numbers = [0, 5, 8, 3, 4, 6, 1]
result = []
while len(numbers) != 0:
    secondresult = []
    for _ in range(3):
        if numbers != []:
            toappend = numbers.pop(0)
            secondresult.append(toappend)
        else:
            continue
    result.append(secondresult)
print(result)

use while and for loops. and append them to secondresult and result

Related