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

如何在Python中按指定位置拆分矩阵并写入CSV文件

解决方案

1. 拆分矩阵

按全零行将原矩阵拆分为多个子矩阵,每个子矩阵以全零行开头,包含后续直到下一个全零行前的所有行:

matrix = [['0','0'],
          ['2','3'],
          ['1','9'],
          ['7','11'], 
          ['1','2'], 
          ['7','23'],
          ['0','0'],
          ['6','8'],
          ['3','1'],
          ['8','1'],
          ['4','3'],
          ['0','0'],
          ['63','9'],
          ['31','10'],
          ['82','11'],
          ['41','31']] 

# 拆分矩阵
submatrices = []
current_sub = []
for row in matrix:
    if row == ['0', '0']:
        if current_sub:
            submatrices.append(current_sub)
            current_sub = []
        current_sub.append(row)
    else:
        current_sub.append(row)
# 加入最后一个子矩阵
submatrices.append(current_sub)

# 查看拆分结果
for idx, sub in enumerate(submatrices, 1):
    print(f"matrix{idx} = {sub}")

运行后即可得到你需要的三个子矩阵。

2. 相邻写入CSV文件

要实现子矩阵横向相邻排列的效果,先对齐所有子矩阵的行数(短矩阵补空行),再逐行拼接各子矩阵的对应行元素(可添加空列分隔),最后写入CSV:

import csv

# 获取最长子矩阵的行数,用于补全行对齐
max_rows = max(len(sub) for sub in submatrices)

# 构造输出每行的内容
output_rows = []
for i in range(max_rows):
    current_row = []
    for sub in submatrices:
        # 取当前子矩阵的第i行,超出长度则补空值
        if i < len(sub):
            current_row.extend(sub[i])
        else:
            current_row.extend(['', ''])
        # 子矩阵间添加空列分隔(不需要可删除此行)
        current_row.append('')
    # 移除最后一个多余的空列
    current_row.pop()
    output_rows.append(current_row)

# 写入CSV文件
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(output_rows)

执行后会生成符合要求的CSV文件,三个子矩阵横向相邻排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:41:05