Make Python signatures from a list using a delimiter

I have, for example, the following list:

['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'] 

and want it to be separated by "|" so the result will look like this:

 [[u'MOM', u'DAD'],[ u'GRAND'], [u'MOM', u'MAX', u'JULES']] 

How can i do this? I find only examples of lists on the net that need element lengths

+9
python split sublist
source share
4 answers
 >>> [list(x[1]) for x in itertools.groupby(['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'], lambda x: x=='|') if not x[0]] [[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']] 
+15
source share

itertools.groupby() does it very well ...

 >>> import itertools >>> l = ['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'] >>> key = lambda sep: sep == '|' >>> [list(group) for is_key, group in itertools.groupby(l, key) if not is_key] [[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']] 
+6
source share

A simple solution using a simple old for-loop (was beaten to solve groupby that BTW is better!)

 seq = ['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'] S=[] tmp=[] for i in seq: if i == '|': S.append(tmp) tmp = [] else: tmp.append(i) # Remove empty lists while True: try: S.remove([]) except ValueError: break print S 

gives

 [[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']] 
+1
source share
 >>> reduce( lambda acc,x: acc+[[]] if x=='|' else acc[:-1]+[acc[-1]+[x]], myList, [[]] ) [[], ['MOM', 'DAD'], ['GRAND'], ['MOM', 'MAX', 'JULES'], []] 

Of course, you would like to use itertools.groupby , although you may notice that my approach "correctly" puts empty lists at the ends. =)

0
source share

All Articles