alinsoar
alinsoar

Reputation: 15783

split a list in python

I have a list of objects, and I wish to get a list of list of objects, splitted using objects from another list, like that:

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

and another list of objects

s = ['a', 1, 4]

And I wish to get the result so:

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

Is there a nice/pythonic way to do it ?

EDIT:

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

Upvotes: 4

Views: 1041

Answers (2)

pradyunsg
pradyunsg

Reputation: 19406

Try these 2 functions,

  1. The '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
    
  2. The 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 (all will be 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))

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121176

A generator would do that for you in a jiffy:

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 could just loop over the generator without creating a full list of course:

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

Upvotes: 5

Related Questions