Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
Vibhutha Kumarage Avatar asked Apr 21 '26 23:04

Vibhutha Kumarage


1 Answers

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]]
like image 54
Transhuman Avatar answered Apr 24 '26 12:04

Transhuman