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

Python读取文件去空格逗号并构建图结构的技术问询

解决方法:将带空格和逗号的图数据转换为可构建图的格式

我明白你现在的问题——要把这种顶点 邻接顶点,权重 邻接顶点,权重...格式的行数据转换成适合构建图的结构,之前用strip()和split(',')没拿到想要的结果对吧?其实是处理顺序的问题,咱们一步步来解决:

核心思路

每一行的结构是:当前顶点 + 多个"邻接顶点,权重"的组合,所以正确的处理顺序应该是:

  1. 先按空格分割行,把当前顶点和所有邻接项分开
  2. 再对每个邻接项按逗号分割,提取邻接顶点和权重
  3. 把这些数据整理成字典(键为顶点,值为邻接列表),方便后续构建图

单行数据处理示例

假设你有一行数据:

1 80,982 163,8164 170,2620 145,648 200,8021 173,2069

用以下代码处理:

# 定义单行数据
line = "1 80,982 163,8164 170,2620 145,648 200,8021 173,2069"

# 第一步:按空格分割,分离当前顶点和邻接项
parts = line.strip().split()
current_vertex = int(parts[0])

# 第二步:处理每个邻接项,提取邻接顶点和权重
adjacency_list = []
for item in parts[1:]:
    neighbor, weight = item.split(',')
    # 转换为整数类型(根据你的需求也可以保留字符串)
    adjacency_list.append((int(neighbor), int(weight)))

# 第三步:构建图结构(字典形式)
graph = {}
graph[current_vertex] = adjacency_list

# 输出结果
print(graph)

运行后会得到:

{1: [(80, 982), (163, 8164), (170, 2620), (145, 648), (200, 8021), (173, 2069)]}

处理整个文件的代码

如果你的数据是保存在文件中的,可以用循环读取每一行并处理:

graph = {}

# 替换成你的文件路径
with open('graph_data.txt', 'r') as file:
    for line in file:
        # 跳过空行
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        
        parts = cleaned_line.split()
        current_vertex = int(parts[0])
        adjacency_list = []
        
        for item in parts[1:]:
            neighbor_str, weight_str = item.split(',')
            adjacency_list.append((int(neighbor_str), int(weight_str)))
        
        graph[current_vertex] = adjacency_list

# 查看最终的图结构
for vertex, adj in graph.items():
    print(f"顶点 {vertex} 的邻接列表:{adj}")

为什么之前的方法没生效?

你之前尝试的strip()只能去除首尾空白,split(',')直接分割整行的话,会把"1 80"这样的内容当成一个元素(因为空格没被处理),所以必须先按空格分割行,再处理每个邻接项的逗号分割。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:07:34