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

Python中不使用列表切片如何按n个元素为一组拆分列表

Python不使用列表切片实现列表按N个元素分组

这里提供两种无需列表切片的实现方案,都可以达到和示例代码完全一致的分组效果:

方案1:遍历元素分组(支持无索引的可迭代对象)

不需要提前获取列表长度,也支持生成器、迭代器这类不支持索引访问的可迭代对象:

theList = list(range(10))
N = 3
subList = []
current_group = []

for item in theList:
    current_group.append(item)
    # 当前组元素数量达到N就存入结果,重置当前组
    if len(current_group) == N:
        subList.append(current_group)
        current_group = []
# 补充最后不足N个元素的剩余组
if current_group:
    subList.append(current_group)

# 输出结果:[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
print(subList)

方案2:按索引步长分组(和原切片逻辑对齐)

逻辑和原切片写法的执行逻辑一致,只是将切片操作替换为逐个按索引取值:

theList = list(range(10))
N = 3
subList = []
list_length = len(theList)

for start_idx in range(0, list_length, N):
    current_group = []
    for offset in range(N):
        target_idx = start_idx + offset
        if target_idx < list_length:
            current_group.append(theList[target_idx])
        else:
            break
    subList.append(current_group)

# 输出结果:[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
print(subList)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:27:08