如何在指定值(1.)出现前拆分列表生成多个子列表?
Solution to Split List at Each Occurrence of
1. Got it, let's tackle this problem step by step. You want to split your original list into sublists where each sublist starts with a 1., splitting right before every occurrence of 1. (we skip the first one since there's nothing before it to split from). Here's a straightforward Python implementation to do this:
Step-by-Step Code Implementation
# Your original list lst = [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0.] # First, find all indices where the element is 1. split_points = [index for index, value in enumerate(lst) if value == 1.] # Split the original list into sublists using these indices sublists = [] for i in range(len(split_points)): start_idx = split_points[i] # For all except the last sublist, end at the next split point if i < len(split_points) - 1: end_idx = split_points[i+1] # For the last sublist, end at the end of the original list else: end_idx = len(lst) sublists.append(lst[start_idx:end_idx]) # Print the result with clear labels like lst1, lst2, etc. for num, sublist in enumerate(sublists, 1): print(f"lst{num} = {sublist}")
Output of the Code
When you run this code, you'll get the following sublists (matching your expected structure, plus the additional sublists from the remaining 1. entries in your original list):
lst1 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]lst2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]lst3 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]lst4 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]lst5 = [1.0, 0.0, 0.0]lst6 = [1.0, 0.0, 0.0, 0.0, 0.0]
How It Works
- Identify Split Points: We use a list comprehension to collect all indices where the element is
1.— these are our starting points for each sublist. - Slice the List: We loop through each split point, creating a sublist from the current split point to the next one (or the end of the list for the last sublist).
- Label and Print: Finally, we iterate over the resulting sublists and print them with sequential labels for clarity.
内容的提问来源于stack exchange,提问作者Divya R
相关产品推荐
相关产品推荐

