The groupby
method is the best one.
group using the key function item != '~'
, and filter on the key being True
(when x=='~'
, the key function returns False
, the if k
condition filters that out)
import itertools
lst = ['~', 'n1', 'n2', 'nn', '~', 'k1', 'k2', 'kn', '~']
result = [list(v) for k,v in itertools.groupby(lst,lambda x : x!='~') if k]
result:
[['n1', 'n2', 'nn'], ['k1', 'k2', 'kn']]
note that you have to force iteration on issued groups, since groupby
returns iterables (just in case you just need to iterate on them again)
If you have empty strings, it's even simpler: no need for lambda
, rely on the truthfullness of the values and use bool
operator:
lst = ['', 'n1', 'n2', 'nn', '', 'k1', 'k2', 'kn', '']
result = [list(v) for k,v in itertools.groupby(lst,bool) if k]