Friday, April 19, 2019

Python split list into sub-lists based on string value


I have a list that is randomly separated by a string value, now I want to make a sub-list at each of the random string that separates the whole list.


in other words as an example, the list below is separated by ':' at random intervals. So, at each occurrence of ':', I want to make a list of those elements.


mylist = [1, 'sistani', ':', 3, ':', 7, 9, 0, 'anita', ':', 20, 8, 4, ':', 12, 5, 10, ':', 56, ':', 6, 30, 56, 'usman', ':']
mysepstring = ':'
# Split list by value - python split list into sublists based on string value
def list_splitz(baseList, sepString):    
    group = []    
    for x in baseList:
        if x != sepString:
            group.append(x)
        elif group:
            yield group
            group = []
            
print(list(list_splitz(mylist, mysepstring)))



Alternative solution....

from itertools import groupby
resulting_list = [list(g) for k, g in groupby(mylist, lambda x: x != mysepstring) if k]



Hope this was useful.

No comments:

Post a Comment