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

如何读取文件中的数字并按分隔符将其存入多个数组?

处理带分隔符的文本文件生成嵌套数组

Python实现方案

可以通过逐行读取文件内容,对数据进行分组处理,代码示例如下:

output = []
current_group = []

# 替换为你的文件路径
with open('numbers.txt', 'r') as file:
    for line in file:
        cleaned_line = line.strip()
        # 跳过空行
        if not cleaned_line:
            continue
        # 遇到分隔符时,将当前组存入结果并重置
        if cleaned_line == '-':
            if current_group:
                output.append(current_group)
                current_group = []
        else:
            # 将文本转为整数,若需保留字符串可去掉int()
            current_group.append(int(cleaned_line))
# 处理文件末尾未被分隔符收尾的最后一组数据
if current_group:
    output.append(current_group)

print(f"output = {output}")

代码说明

  • 初始化结果数组output和临时存储当前组的current_group
  • 打开目标文件后逐行读取,先去除每行的换行符和首尾空格
  • 遇到分隔符-时,将当前已收集的数字组添加到结果数组,然后重置临时组
  • 非分隔符的行转换为整数后加入临时组
  • 循环结束后检查临时组是否有剩余数据,避免遗漏最后一组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:24:08