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

如何使用Python读取含BUS标记的文本文件并将内容赋值为3D列表

实现方法

你可以通过逐行遍历文本、按BUS标识分组的方式完成转换,以下是可直接运行的代码:

def parse_bus_3d_list(file_path):
    final_3d_list = []
    current_matrix = None
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            # 清除首尾空格、跳过空行
            cleaned_line = line.strip()
            if not cleaned_line:
                continue
            # 识别BUS分组标识
            if cleaned_line.startswith('BUS'):
                current_matrix = []
                final_3d_list.append(current_matrix)
                continue
            # 处理数字行,转换为整数列表
            num_row = list(map(int, cleaned_line.split()))
            current_matrix.append(num_row)
    return final_3d_list

# 测试调用
if __name__ == "__main__":
    result = parse_bus_3d_list("你的文本文件路径.txt")
    print(result)

运行上述代码后输出结果和你给出的示例完全一致:
[[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]], [[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]

逻辑说明

  • 逐行读取文本时先过滤空行,避免格式干扰
  • 遇到BUS开头的行就新建一个空的二维矩阵,加入最终的3D列表中
  • 普通数字行直接按空格分割、转成整数后追加到当前分组的二维矩阵中,自动适配不同长度的行

可选变种:按BUS号映射的字典

如果你需要通过BUS编号直接获取对应矩阵,可以改用字典存储结果:

def parse_bus_to_dict(file_path):
    bus_map = {}
    current_bus_id = None
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            cleaned_line = line.strip()
            if not cleaned_line:
                continue
            if cleaned_line.startswith('BUS'):
                current_bus_id = int(cleaned_line.split()[1])
                bus_map[current_bus_id] = []
                continue
            num_row = list(map(int, cleaned_line.split()))
            bus_map[current_bus_id].append(num_row)
    return bus_map

返回结果格式示例:{0: [[0,1,2,3], [0,4,1,9,2,3]], 1: [[0,1,9,2,3], [0,1,2,3], [0,1,2,3]]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:45:05