You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在指定值(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

  1. 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.
  2. 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).
  3. Label and Print: Finally, we iterate over the resulting sublists and print them with sequential labels for clarity.

内容的提问来源于stack exchange,提问作者Divya R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:52:31