| Version 2 (modified by , 15 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:
- Initialize an empty result list: This will hold the final split sublists.
- Iterate through each sublist: Check if the first element of the sublist is the given symbol.
- When the symbol is found: Start a new group in the result list.
- 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.
![(please configure the [header_logo] section in trac.ini)](/playground/chrome/site/playground.png)