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

Python使用for循环实现列表分批时的输出格式调整问题咨询

问题原因

你当前直接将chunks生成器转为整体列表后打印,所以输出了嵌套的二维列表结构。该需求不需要用到return,直接遍历生成器返回的每个子列表,逐行打印并插入分隔线即可实现预期效果。

修改后代码

a=[1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
        
def hello():
    s = chunks(a, 10)
    for idx, chunk in enumerate(s):
        # 非首个分块前打印分隔线
        if idx > 0:
            print("---------New line----")
        print(chunk)

hello()

运行输出

[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
---------New line----
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]

该写法适配任意数量的分块,会自动在每两个相邻分块之间插入分隔线,无需手动调整逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:06:03