基于'-break-'拆分列表:提取分隔符间元素组并生成新列表
Solution to Split List by '-break-' Markers
Here's a straightforward Python approach to split your main list into groups separated by '-break-' and collect those groups into a new list:
# Note: Corrected a syntax error in the input (added comma after 'six') to make it valid Python main_list = [ '-break-', 'one', 'two', '-break-', 'three', '-break-', 'four', 'five', 'six', '-break-', 'seven', 'eight', 'nine', 'ten' ] new_list = [] current_group = [] for item in main_list: if item == '-break-': if current_group: # Only add non-empty groups to avoid empty entries new_list.append(current_group) current_group = [] # Reset the temporary group for the next set of elements else: current_group.append(item) # Capture the final group of elements after the last '-break-' marker if current_group: new_list.append(current_group) print(new_list)
Output:
[['one', 'two'], ['three'], ['four', 'five', 'six'], ['seven', 'eight', 'nine', 'ten']]
How It Works:
- Initialization: We start with an empty
new_listto store our final groups and an emptycurrent_groupto build each group as we iterate through the input. - Loop Through Elements: For each item in
main_list:- When we hit a '-break-' marker, we check if
current_grouphas elements. If it does, we add the group tonew_listand resetcurrent_groupto start collecting the next set of items. - For non-marker items, we simply add them to
current_group.
- When we hit a '-break-' marker, we check if
- Final Group Check: After the loop finishes, we make sure to add any remaining elements in
current_group(since there’s no '-break-' marker after the last set of items in your input).
This approach handles edge cases like leading markers, single-element groups, and trailing elements cleanly.
内容的提问来源于stack exchange,提问作者Becay
相关产品推荐
相关产品推荐

