Search code examples
pythonlistpython-itertools

Take sequence of values from a python list


I have a array like this,

a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]

and I want to make list of values that are lesser than 7 (look like following)

b = [[3,2,5],[4,5,6,3],[4,5],[5],[4],[6]]

So I used following method,

>>> from itertools import takewhile
>>> a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]
>>>list(takewhile(lambda x: x < 7 , a))
[3, 2, 5]

But I only get the first sequence. Can anyone help me to solve this problem ? Thank you.


Solution

  • a = [3,2,5,7,4,5,6,3,8,4,5,7,8,9,5,7,8,4,9,7,6]
    from itertools import groupby
    [list(g) for k, g in groupby(a, lambda x:x<7) if k]
    

    Output:

    [[3, 2, 5], [4, 5, 6, 3], [4, 5], [5], [4], [6]]