Split list into chunks defined by delimiter

I have this list (python):

[item1], [item2], [item3], [/], [item4], [item5], [item6], [/] ... etc.

I want to split them into pieces, and the elements that will go into each piece are the elements before the "/" separator.

So my pieces will look like this:

block 1: [element1], [element2], [element3] chunk2: [item4], [Item5], [item6]

I tried and tried, nothing effective came to mind. Make your way through it with the for and and if [x] == '/' element, then get some positions. It is very dirty and does not work properly.

Any help would be appreciated.

+4
source share
3 answers

itertools.groupby, :

>>> 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']

( [item1],[item2],[item3],[/], , , , ['/'] .)

+5

- - '/', . itertools.groupby , - , , .

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

, , python - - ' ' (), '/', ' ' .

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
+2

This can also be done as (assuming empty fragments are undesirable, and l is a list that should 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)
+2
source

All Articles