Cemre Cemre - 1 month ago 13
Python Question

Python spliting a list based on a delimiter word

I have a list containing various string values. I want to split the list whenever I see

WORD
. The result will be a list of lists (which will be the sublists of original list) containing exactly one instance of the
WORD
I can do this using a loop but is there a more pythonic way to do achieve this ?

Example =
['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']


result =
[['A'], ['WORD','B','C'],['WORD','D']]


This is what I have tried but it actually does not achieve what I want since it will put
WORD
in a different list that it should be in:

def split_excel_cells(delimiter, cell_data):

result = []

temp = []

for cell in cell_data:
if cell == delimiter:
temp.append(cell)
result.append(temp)
temp = []
else:
temp.append(cell)

return result

NPE NPE
Answer

I would use a generator:

def group(seq, sep):
    g = []
    for el in seq:
        if el == sep:
            yield g
            g = []
        g.append(el)
    yield g

ex = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']
result = list(group(ex, 'WORD'))
print(result)

This prints

[['A'], ['WORD', 'B', 'C'], ['WORD', 'D']]

The code accepts any iterable, and produces an iterable (which you don't have to flatten into a list if you don't want to).

Comments