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

仅用Python标准库实现CSV转三角矩阵的代码重构与优化

CSV转下三角矩阵的Python标准库优化实现

需求说明

现有如下格式的CSV文件,每行存储两个关联节点及对应权重:

A,B,0.5
A,C,0.4
A,D,0.2
B,C,0.7
B,D,0.6
C,D,0.9

需要转换为下三角矩阵格式(空格仅为可读性示例,实际输出可省略):

,A  ,B  ,C  ,D
B,0.5,   ,   ,
C,0.4,0.7,   ,
D,0.2,0.6,0.9,

仅可使用Python标准库实现,不可引入第三方依赖。

优化方案

核心优化点

  1. Part2 索引收集逻辑简化:用集合推导式替代多层循环收集行索引,代码更紧凑可读性更高
  2. Part3 行拼接逻辑简化:用列表推导式替代循环判断拼接,运行效率更高

优化后基础版代码(输出CSV格式矩阵)

from csv import reader
from collections import defaultdict

# 读取CLI参数部分省略
with open(args.path, 'r') as infile:
    matrix = defaultdict(dict)
    for u, v, weight in reader(infile):
        matrix[u][v] = float(weight)

# 优化后的索引生成逻辑
cols = list(matrix)
# 集合推导式一次性收集所有行索引,排序逻辑和原代码保持一致
rows = sorted(
    {v for u in matrix for v in matrix[u]},
    key=lambda x: len(matrix.get(x, {})),
    reverse=True
)

# 优化后的输出逻辑
print(',' + ','.join(cols))
for row in rows:
    curr_row = [str(matrix[col][row]) if row in matrix[col] else '' for col in cols]
    print(f"{row},{','.join(curr_row)}")

可选美化输出版代码

from csv import reader
from collections import defaultdict

with open(args.path, 'r') as infile:
    matrix = defaultdict(dict)
    all_nodes = set()
    for u, v, weight in reader(infile):
        matrix[u][v] = float(weight)
        all_nodes.update([u, v])

# 统一按字母排序节点,可根据需求调整排序规则
nodes = sorted(all_nodes)
cell_width = 6

# 输出表头
header = ''.join(f'{n:^{cell_width}}' for n in nodes)
print(f'[{header}]')

# 输出每行内容
for row_idx, row_node in enumerate(nodes[1:], 1):
    cells = []
    for col_idx in range(row_idx):
        col_node = nodes[col_idx]
        cells.append(f'{matrix[col_node][row_node]:<{cell_width}}')
    print(f'[{row_node}] {"".join(cells)}')

运行美化版代码可得到如下输出:

[   A    B    C    D   ]
[B] 0.5   
[C] 0.4   0.7   
[D] 0.2   0.6   0.9   

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:54:03