Answer a question

Given a list like:

[a, SEP, b, c, SEP, SEP, d]

how do I split it into a list of sublists:

[[a], [b, c], [], [d]]

Effectively I need an equivalent of str.split() for lists. I can hack together something, but I can't seem to be able to come up with anything neat and/or pythonic.

I get the input from an iterator, so a generator working on that is acceptable as well.

More examples:

[a, SEP, SEP, SEP] -> [[a], [], [], []]

[a, b, c] -> [[a, b, c]]

[SEP] -> [[], []]

Answers

A simple generator will work for all of the cases in your question:

def split(sequence, sep):
    chunk = []
    for val in sequence:
        if val == sep:
            yield chunk
            chunk = []
        else:
            chunk.append(val)
    yield chunk
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐