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

如何使用Python while循环按阈值对数字列表进行分组

阈值分组代码问题修复

错误原因

你当前的代码仅实现了单次分组的处理逻辑,缺少外层循环遍历全量列表的控制逻辑:

  • 单层while循环只会处理到第一个累加超阈值的位置就停止
  • else分支仅执行一次就走到return语句,不会继续处理列表剩余的元素

修复后代码

def group_numbers(num_list, threshold):
    i = 0 
    total = 0
    temp_list = []
    result_list = []
    # 外层循环控制遍历完全部元素
    while i < len(num_list):
        # 累加当前元素不超阈值就加入当前分组
        if total + num_list[i] <= threshold:
            total += num_list[i]
            temp_list.append(num_list[i])
            i += 1
        # 超过阈值就结束当前分组
        else:
            result_list.append(temp_list)
            total = 0
            temp_list = []
    # 遍历结束后把最后一个分组加入结果
    if temp_list:
        result_list.append(temp_list)
    return result_list

测试验证

调用示例:

print(group_numbers([1,2,3,2,5,6,2], 8))

输出结果:

[[1, 2, 3, 2], [5], [6, 2]]

和预期结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:27:02