Changes between Version 1 and Version 2 of SplitLists


Ignore:
Timestamp:
08/14/24 14:23:05 (9 months ago)
Author:
Enrico Schwass
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • SplitLists

    v1 v2  
    1 Test
     1### Given:
     2- You have a list of lists.
     3- You want to split each sublist at the point where the sublist starts with a given symbol.
     4
     5### Example:
     6
     7#### Input:
     8{{{#!python
     9list_of_lists = [
     10    ['a', 1, 2, 3],
     11    ['b', 4, 5, 6],
     12    ['*', 7, 8, 9],
     13    ['c', 10, 11],
     14    ['*', 12, 13],
     15    ['d', 14, 15, 16]
     16]
     17symbol = '*'
     18}}}
     19
     20#### Expected Output:
     21{{{#!python
     22[
     23    [['a', 1, 2, 3], ['b', 4, 5, 6]],
     24    [['*', 7, 8, 9], ['c', 10, 11]],
     25    [['*', 12, 13], ['d', 14, 15, 16]]
     26]
     27}}}
     28
     29### Steps:
     30
     311. **Initialize an empty result list**: This will hold the final split sublists.
     322. **Iterate through each sublist**: Check if the first element of the sublist is the given symbol.
     333. **When the symbol is found**: Start a new group in the result list.
     344. **Continue grouping until the symbol is encountered again**.
     35
     36### Python Code Implementation:
     37
     38{{{#!python
     39def split_list_of_lists(list_of_lists, symbol):
     40    result = []
     41    current_group = []
     42   
     43    for sublist in list_of_lists:
     44        if sublist[0] == symbol and current_group:
     45            result.append(current_group)
     46            current_group = []
     47        current_group.append(sublist)
     48   
     49    if current_group:
     50        result.append(current_group)
     51   
     52    return result
     53
     54# Example usage
     55list_of_lists = [
     56    ['a', 1, 2, 3],
     57    ['b', 4, 5, 6],
     58    ['*', 7, 8, 9],
     59    ['c', 10, 11],
     60    ['*', 12, 13],
     61    ['d', 14, 15, 16]
     62]
     63symbol = '*'
     64output = split_list_of_lists(list_of_lists, symbol)
     65print(output)
     66}}}
     67
     68### Output:
     69{{{#!python
     70[
     71    [['a', 1, 2, 3], ['b', 4, 5, 6]],
     72    [['*', 7, 8, 9], ['c', 10, 11]],
     73    [['*', 12, 13], ['d', 14, 15, 16]]
     74]
     75}}}