Split list into lists based on a character occurring inside of an element

Viewed 28180

In a list like the one below:

biglist = ['X', '1498393178', '1|Y', '15496686585007',
           '-82', '-80', '-80', '3', '3', '2', '|Y', '145292534176372',
           '-87', '-85', '-85', '3', '3', '2', '|Y', '11098646289856',
           '-91', '-88', '-89', '3', '3', '2', '|Y', '35521515162112',
           '-82', '-74', '-79', '3', '3', '2', '|Z',
           '0.0', '0.0', '0', '0', '0', '0', '0', '4', '0', '154']

There could be some numerical elements preceded by a character. I would like to break this into sub-lists like below:

smallerlist = [
 ['X', '1498393', '1'],
 ['Y', '1549668', '-82', '-80', '-80', '3', '3', '2', ''],
 ['Y', '1452925', '-87', '-85', '-85', '3', '3', '2', ''],
 ['Y', '3552151', '-82', '-74', '-79', '3', '3', '2', ''],
 ['Z', '0.0', '0.0', '0', '0', '0', '0', '0', '4', '0', '154']
]

As you can tell, depending upon the character, the lists could look similar. Otherwise they could have a different number of elements, or dissimilar elements altogether. The main separator is the "|" character. I have tried to run the following code to split up the list, but all I get is the same, larger, list within a list. I.e., list of len(list) == 1.

import itertools

delim = '|'
smallerlist = [list(y) for x, y in itertools.groupby(biglist, lambda z: z == delim)
                if not x]

Any ideas how to split it up successfully?

4 Answers

Here is a solution to a similar problem I didn't find an answer to. How to split a list into sublists delimited by a member, e.g. character:

l = ['r', 'g', 'b', ':',
     'D', 'E', 'A', 'D', '/',
     'B', 'E', 'E', 'F', '/',
     'C', 'A', 'F', 'E']

def split_list(thelist, delimiters):
    ''' Split a list into sub lists, depending on a delimiter.

        delimiters - item or tuple of item
    '''
    results = []
    sublist = []

    for item in thelist:
        if item in delimiters:
            results.append(sublist) # old one
            sublist = []            # new one
        else:
            sublist.append(item)

    if sublist:  # last bit
        results.append(sublist)

    return results


print(
    split_list(l, (':', '/'))
)
# => [['r', 'g', 'b'], ['D', 'E', 'A', 'D'], 
#     ['B', 'E', 'E', 'F'], 
#     ['C', 'A', 'F', 'E']]
Related