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

如何将Python列表元素按每3个一组分行写入文本文件?

解决方案

你现有代码的问题是将所有列表元素一次性拼接为单个字符串写入,所以全部内容会出现在同一行。只需要先把列表按3个元素为一组拆分,每组单独拼接为一行字符串写入即可实现需求。

调整后代码(兼容你原有写法)

prog_input = [120,0,0,100,20,0,100,0,20]
txtfile1 = open("Input progression data.txt", "w+")
# 按步长3遍历列表索引,拆分出每3个元素为一组
for i in range(0, len(prog_input), 3):
    current_group = prog_input[i:i+3]
    txtfile1.write(', '.join(map(str, current_group)) + '\n')
txtfile1.close()

更推荐的写法(使用with上下文管理器,自动管理文件句柄,无需手动关闭)

prog_input = [120,0,0,100,20,0,100,0,20]
with open("Input progression data.txt", "w+") as txtfile1:
    # 批量生成所有行的内容
    output_lines = [', '.join(map(str, prog_input[i:i+3])) for i in range(0, len(prog_input), 3)]
    txtfile1.write('\n'.join(output_lines))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:36:03