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

Python如何拆分列表实现按指定数量批量拼接输出文本

实现方案

核心修改逻辑

  • 新增可自定义的分组大小参数,调整该参数即可控制每组包含的数字数量
  • 用Python列表切片实现列表分组,语法为列表[起始索引:结束索引],循环步长设为分组大小即可遍历所有分组
  • 单次打开输出文件,循环写入每一行内容,每行末尾追加换行符\n实现分行效果
  • 额外加入空值过滤逻辑,避免ids.txt首尾/中间出现多余空格导致的内容异常

完整可运行代码

def idcommands(contentsplit, group_size):
    # 用with上下文管理器管理文件,自动处理关闭,无需手动调用close
    with open('command.txt', 'w', encoding='utf-8') as textfile:
        # 按指定大小切割列表
        for i in range(0, len(contentsplit), group_size):
            current_group = contentsplit[i:i+group_size]
            # 拼接当前组内容
            command_line = ' and '.join(current_group)
            # 写入行内容并追加换行符
            textfile.write(f"Hello {command_line}\n")

def main():
    # 自定义每组数字数量,示例效果为4个一组,可根据需求修改
    group_count = 4
    with open("ids.txt", "r", encoding='utf-8') as file:
        content = file.read().strip()
        # 拆分后过滤空字符串,避免多余空格导致的异常
        contentsplit = [item for item in content.split(' ') if item]
    idcommands(contentsplit, group_count)

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:27:03