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

Python如何将嵌套数组列表导出为指定格式的TXT文件?

问题:将嵌套NumPy数组列表导出为指定格式的TXT文件

示例数据

import numpy as np
x = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]

期望输出格式

(0,0,0),(1,2,2)
(0,0,0),(4,5,6)

已尝试但无效的方法

  • 使用np.savetxt:

    # Trial1
    np.savetxt(full_path, x, delimiter = ',')
    

    报错:Error: Expected 1D or 2D array, got 3D array instead

  • 使用np.save:

    # Trial2
    np.save(full_path, x, allow_pickle=True)
    

    无法实现,无法处理pickle的扩展名。

  • 使用Pandas:

    # Trial3
    import pandas as pd
    df = pd.DataFrame(x)
    print(df.to_csv(index=False, header=False))
    

    输出接近但不符合要求:

    [0 0 0],[1 2 2]
    [0 0 0],[4 5 6]
    

可行解决方法

方法一:手动遍历+字符串格式化

直接遍历嵌套结构,将每个NumPy数组转换为指定格式的字符串后写入文件:

import numpy as np

x = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]
full_path = "output.txt"

with open(full_path, "w") as f:
    for row in x:
        # 将单个数组转为(元素1,元素2,元素3)格式
        formatted_items = [f"({','.join(map(str, arr))})" for arr in row]
        # 拼接成一行写入
        f.write(','.join(formatted_items) + '\n')

逻辑直观,完全匹配目标格式,无额外依赖。

方法二:数组扁平化+NumPy格式化输出

先将嵌套数组转为二维数组,再利用np.savetxt的格式化参数输出:

import numpy as np

x = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]
full_path = "output.txt"

# 将嵌套数组转为(n,6)的二维数组
flat_arr = np.array(x).reshape(len(x), -1)
# 定义每行的输出格式
line_fmt = "({0},{1},{2}),({3},{4},{5})"

np.savetxt(full_path, flat_arr, fmt=line_fmt, delimiter='')

适合数据规模较大的场景,利用NumPy的数组操作简化流程。

方法三:优化Pandas输出

针对之前的Pandas结果,修改元素格式并禁用引号即可:

import pandas as pd
import numpy as np

x = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]
full_path = "output.txt"

# 先将所有数组转为目标格式的字符串
formatted_x = [[f"({','.join(map(str, arr))})" for arr in row] for row in x]
df = pd.DataFrame(formatted_x)
# 导出时禁用所有引号
df.to_csv(full_path, index=False, header=False, quoting=3)

quoting=3参数会去除CSV默认添加的引号,刚好符合输出要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:25:26