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

为何列表分块代码中的嵌套while循环陷入无限循环?

问题原因及修复方案

你的代码陷入无限循环的核心问题,以及其他需要修正的点如下:

  • 外层循环索引i从未递增:外层while i < len(list1)的循环里,没有任何代码推进i的数值,每次外层循环都停在i=0,永远满足循环条件,直接导致无限循环。
  • 内层循环条件错误:counter <= chunk会让循环执行chunk+1次(比如chunk=2时,counter从0到2,共3次),无法得到指定长度的子列表,应该改成counter < chunk。
  • 列表引用错误:内层代码里写了list[i],但你的源列表变量是list1,这里会触发NameError,而且每次添加元素后需要递增i,否则会一直重复添加同一个元素。

修复后的代码

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
i = 0 
chunk = 2 
list2 = [] 
while i < len(list1): 
    element = [] 
    counter = 0 
    # 修正内层循环条件,同时避免i越界
    while counter < chunk and i < len(list1): 
        element.append(list1[i])
        counter += 1 
        i += 1  # 推进源列表索引,避免重复取同一元素
    list2.append(element) 
print(list2)

运行结果:[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:45:42