简体   繁体   中英

How can I split a List (in python) in different parts (after a certain element)?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM