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

如何让迭代从断点继续向多列表追加元素而非从头开始?

解决方案

你的问题核心是每次填充test的子列表时,都从头遍历mylist,没有记录上次停止的位置。只需要加一个变量跟踪当前处理到mylist的索引,就能实现断点续填。

修正后的代码:

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
time = [2, 2, 2, 5, 1, 6, 5, 1]

test = [[], [], [], []]
totaltime = 0
current_idx = 0  # 跟踪当前处理到mylist的哪个位置

for i in range(len(test)):
    # 从current_idx开始遍历,而非从头开始
    while current_idx < len(mylist) and totaltime < 6:
        test[i].append(mylist[current_idx])
        totaltime += time[current_idx]
        current_idx += 1
    totaltime = 0  # 重置时间,准备填充下一个子列表

print(test)

关键改动说明:

  • 新增current_idx变量,初始为0,专门记录当前处理到mylist的索引位置。
  • 把内层的for循环改成while循环,条件设置为current_idx未到mylist末尾,且累计时间小于6。这样每次填充子列表时,都会从上次停止的位置继续。
  • 每添加一个元素,current_idx自增1,确保下一次处理时不会重复添加之前的元素。
  • 当累计时间达到或超过6,或者mylist元素处理完时,停止当前子列表的填充,重置时间后处理下一个子列表。

运行这段代码后,输出就是你想要的结果:

[[1, 2, 3], [4, 5], [6], [7, 8]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:45:47