'Split a list into nested list at points where item matches criteria

I would like to split a list at points where an item is over a certain length.

a simplified version of my data is:

li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]

the outcome I am trying to achieve is as below

new_li = [[1,2,3],[4000,5,6,7,8],[9000,10,11,12,1300]]

I am new to programming and a little stumped on the approach to this problem.

I am considering looping through and creating an index each time an items length is greater than 2 but am lost as to how I would recreate the nested lists.



Solution 1:[1]

from itertools import groupby

li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]

class GroupbyHelper(object):

    def __init__(self, val):
        self.val = val
        self.i = 0

    def __call__(self, val):
        self.i += (val > self.val)
        return self.i


>>> [list(g) for k, g in groupby(li, key=GroupbyHelper(2000))]
[[1, 2, 3], [4000, 5, 6, 7, 8], [9000, 10, 11, 12, 1300]]

Solution 2:[2]

It could possibly be more efficient to use slices instead of re-appending each item:

li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
res = []
indices = (i for i, v in enumerate(li) if v > 2000)
i = 0
for i2 in indices:
    res.append(li[i:i2])
    i = i2
res.append(li[i:])

edit

Much shorter version:

li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
indices = [i for i, v in enumerate(li) if v > 2000]
res = [li[i:j] for i, j in zip([0]+indices, indices+[None])]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 njzk2