Lets say I have a list that looks like:
[
[],
['blah','blah'],
['a','b'],
[],
['abc','2'],
['ff','a'],
['test','a'],
[],
['123','1'],
[]
]
How do I break this list into list of lists when it encounters an empty item
so list[0] would have :
['blah','blah']
['a','b']
list[1] would have:
['abc','2']
['ff','a']
['test','a']
You can use itertools.groupby, using bool as the key:
from itertools import groupby
lst = [list(v) for k,v in groupby(l, key=bool) if k]
Demo:
In [22]: from itertools import groupby
In [23]: lst = [list(v) for k,v in groupby(l,key=bool) if k]
In [24]: lst[1]
Out[24]: [['abc', '2'], ['ff', 'a'], ['test', 'a']]
In [25]: lst[0]
Out[25]: [['blah', 'blah'], ['a', 'b']]
k will be False for each empty list and True for all non-empty lists.
In [26]: bool([])
Out[26]: False
In [27]: bool([1])
Out[27]: True
In [28]: bool([1,1,3])
Out[28]: True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With