Smash list in python

I have a list of objects and I want to get a list of a list of objects separated using objects from another list, for example:

l = ['x',1,2,3,'a',5,6,1,7] 

and another list of objects

 s = ['a', 1, 4] 

And I want to get the result like this:

 [ ['x'], [1, 2, 3], ['a', 5, 6], [1, 7] ] 

Is there a good / pythonic way to do this?

EDIT:

I want the head of each listed list to be an s element, and all these lists keep the elements of the original list in the same order.

+4
source share
2 answers

Try these 2 functions,

  • Return type

     def overlap_split_list(l,s): l1 = [] l2 = [] for i in l: if i in s: l1.append(l2) l2 = [] l2.append(i) if l2: l1.append(l2) return l1 
  • Generator type

     def generator_overlap_split_list(l,s): l2 = [] for i in l: if i in s: yield l2 l2 = [] l2.append(i) if l2: yield l2 

For output (everything will be the same)

 print overlap_split_list(l,s) print [i for i in generator_overlap_split_list(l,s)] print list(generator_overlap_split_list(l,s)) 
+2
source

The generator will do this for you in an instant:

 def split_on_members(seq, s): s = set(s) chunk = [] for i in seq: if i in s and chunk: yield chunk chunk = [] chunk.append(i) if chunk: yield chunk 

which gives:

 >>> list(split_on_members(l, s)) [['x'], [1, 2, 3], ['a', 5, 6], [1, 7]] 

You can simply iterate over the generator without creating a complete list, of course:

 >>> for group in split_on_members(l, s): ... print group ... ['x'] [1, 2, 3] ['a', 5, 6] [1, 7] 
+5
source

All Articles