wiki:SplitLists

Version 2 (modified by Enrico Schwass, 9 months ago) ( diff )

--

### Given:

  • You have a list of lists.
  • You want to split each sublist at the point where the sublist starts with a given symbol.

### Example:

#### Input:

list_of_lists = [
    ['a', 1, 2, 3],
    ['b', 4, 5, 6],
    ['*', 7, 8, 9],
    ['c', 10, 11],
    ['*', 12, 13],
    ['d', 14, 15, 16]
]
symbol = '*'

#### Expected Output:

[
    [['a', 1, 2, 3], ['b', 4, 5, 6]],
    [['*', 7, 8, 9], ['c', 10, 11]],
    [['*', 12, 13], ['d', 14, 15, 16]]
]

### Steps:

  1. Initialize an empty result list: This will hold the final split sublists.
  2. Iterate through each sublist: Check if the first element of the sublist is the given symbol.
  3. When the symbol is found: Start a new group in the result list.
  4. Continue grouping until the symbol is encountered again.

### Python Code Implementation:

def split_list_of_lists(list_of_lists, symbol):
    result = []
    current_group = []
    
    for sublist in list_of_lists:
        if sublist[0] == symbol and current_group:
            result.append(current_group)
            current_group = []
        current_group.append(sublist)
    
    if current_group:
        result.append(current_group)
    
    return result

# Example usage
list_of_lists = [
    ['a', 1, 2, 3],
    ['b', 4, 5, 6],
    ['*', 7, 8, 9],
    ['c', 10, 11],
    ['*', 12, 13],
    ['d', 14, 15, 16]
]
symbol = '*'
output = split_list_of_lists(list_of_lists, symbol)
print(output)

### Output:

[
    [['a', 1, 2, 3], ['b', 4, 5, 6]],
    [['*', 7, 8, 9], ['c', 10, 11]],
    [['*', 12, 13], ['d', 14, 15, 16]]
]
Note: See TracWiki for help on using the wiki.