0

Having a list that contains strings, I want to split the list at each point where it contains the empty string (''), e.g.

['this', 'is', '', 'an', 'example']

should become

[['this', 'is'], ['an', 'example']]

I wrote a generator that does this:

def split(it, delimiter):
    it = iter(it)
    buffer = []
    while True:
        element = next(it)
        if element != delimiter:
            buffer.append(element)
        elif buffer:
            yield buffer
            buffer = []

Since this looks pretty general, I was wondering if I missed some similar function or related pattern in itertools or somewhere else...?

Thijs van Dien
  • 6,516
  • 1
  • 29
  • 48

2 Answers2

3
>>> from itertools import groupby
>>> words = ['this', 'is', '', 'an', 'example']
>>> [list(g) for k, g in groupby(words, ''.__ne__) if k]
[['this', 'is'], ['an', 'example']]
>>> [list(g) for k, g in groupby(words, 'is'.__ne__) if k]
[['this'], ['', 'an', 'example']]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • I think I would use a lambda function here rather than `''.__ne__`, but the idea is the same and this does the trick nicely. +1. – mgilson May 03 '13 at 13:12
  • How to understand `k` in this context? – Thijs van Dien May 03 '13 at 13:17
  • @ThijsvanDien `''.__ne__`, checks if each item is not equal to `''` if `k` is `True`, then the item was unequal to `''`,so use it, if `k` is `False`, then the item was `equal` to `''` so it skips it. – jamylak May 03 '13 at 13:19
0

You could simply slice the list, all you have to do is find the index of delimiter.

Community
  • 1
  • 1
Tymoteusz Paul
  • 2,732
  • 17
  • 20