Reputation: 5
I have the following problem. I've got a list with elements. For example:
L = ['@@', ' n', ' .', ' ', '-\\', '@@', '+A', '+u', '@@', '+g', '+r', '+u']
Now, I would like to split the List after every '@@', that I get the following:
L1 = ['@@', ' n', ' .', ' ', '-\\']
L2 = ['@@', '+A', '+u']
L3 = ['@@', '+g', '+r', '+u']
I tried a lot but I have no idea, how to do it.
Upvotes: 0
Views: 58
Reputation: 131
Could you define a function to do this? For instance,
def split_list(list, delimiter):
out_list = []
for element in list:
if element == delimiter:
out_list.append([element])
else:
out_list[-1] = out_list[-1].append(element)
return out_list
Upvotes: 0
Reputation: 1122582
You could use a generator function:
def split_by(iterable, split_by):
group = []
for elem in iterable:
if elem == split_by:
if group:
yield group
group = []
group.append(elem)
if group:
yield group
then use that as:
groups = list(split_by(L, '@@))
or use a loop:
for group in split_by(L, '@@'):
print group
Demo:
>>> def split_by(iterable, split_by):
... group = []
... for elem in iterable:
... if elem == split_by:
... if group:
... yield group
... group = []
... group.append(elem)
... if group:
... yield group
...
>>> L = ['@@', ' n', ' .', ' ', '-\\', '@@', '+A', '+u', '@@', '+g', '+r', '+u']
>>> for group in split_by(L, '@@'):
... print group
...
['@@', ' n', ' .', ' ', '-\\']
['@@', '+A', '+u']
['@@', '+g', '+r', '+u']
Upvotes: 1