Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: break list into pieces when an empty entry is found

Tags:

python

list

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']
like image 334
user3711455 Avatar asked Apr 23 '26 10:04

user3711455


1 Answers

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
like image 106
Padraic Cunningham Avatar answered Apr 25 '26 01:04

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!