Split a list into chunks determined by a separator

I wrote something simpler for you to understand - Basically look out for '/', if it's not there keep appending to chunks. itertools.groupby would be worth learning, but something simpler that one understands first is a good idea to start with.

l = ['i1', 'i2', 'i3', '/', 'i4', 'i5', 'i6', '/']

chunks = []
x = 0
chunks.append([])   # create an empty chunk to which we'd append in the loop
for i in l:
    if i != '/':
        chunks[x].append(i)
    else:
        x += 1
        chunks.append([])

print chunks

If your elements are strings, there's a faster way to do what I have done in python - basically - first create a ' ' (space) separated string and then, first split by '/' and then by ' ' again.

l = ['i1', 'i2', 'i3', '/', 'i4', 'i5', 'i6', '/']

s = " ".join(l)  # first create a string, joining by a <space> it could be anything

chunks2 = [x.split() for x in s.split("/")]
print chunks2

This can also be done as (assuming empty chunks are not desired and l is the list to be "chunked"):

chunks, last_chunk = [], []
for x in l:
    if x == '/':
         if last_chunk:
             chunks.append(last_chunk)
             last_chunk = []
    else:
         last_chunk.append(x)
if last_chunk:
    chunks.append(last_chunk)

The usual approach for collecting contiguous chunks is to use itertools.groupby, for example:

>>> from itertools import groupby
>>> blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/']
>>> chunks = (list(g) for k,g in groupby(blist, key=lambda x: x != '/') if k)
>>> for chunk in chunks:
...     print(chunk)
...     
['item1', 'item2', 'item3']
['item4', 'item5', 'item6']

(Your representation of your list [item1],[item2],[item3],[/], makes it look like each of your elements in the list is actually a list, in which case the same approach will work, you simply need to compare against ['/'] or whatever your separator is.)

Tags:

Python

Split