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

Python写入含字符串与数值的多格式数组到文件报错如何解决

错误原因
  • 误用np.array_str():该函数会把完整的字符串数组转换为单个长字符串,而非保留每个字符串为独立元素,直接导致后续合并数组时维度、结构不符合写入要求
  • 直接调用np.array([coord, out_arr])合并数值数组和字符串时,numpy会自动将所有元素转为统一类型,无法保留「数值+字符串」的异构结构
  • 使用zip作为变量名,覆盖了Python内置的zip函数,属于不规范的命名行为
修复方案1(沿用numpy savetxt逻辑)
import numpy as np 
coord = np.linspace(0, 10, 5)
keyy = "LE"
key = np.repeat(keyy, 5)
# 构造异构结构化数组
out_arr = np.zeros(coord.shape[0], dtype=[('num', 'f8'), ('str', 'U2')])
out_arr['num'] = coord
out_arr['str'] = key
# 写入文件
np.savetxt("nam.dat", out_arr, fmt="%f %s")
修复方案2(完全对齐Matlab fprintf逻辑,更灵活)

如果习惯Matlab的逐行写入逻辑,可以直接用Python原生文件操作实现,写法和fprintf几乎一致:

import numpy as np 
coord = np.linspace(0, 10, 5)
keyy = "LE"
key = np.repeat(keyy, 5)
# 等价于Matlab的fopen打开文件
with open("nam.dat", "w") as f:
    for num_val, str_val in zip(coord, key):
        # 等价于Matlab的fprintf(f, '%f %s\n', num_val, str_val)
        f.write("%f %s\n" % (num_val, str_val))
最终输出效果

两种方案生成的nam.dat内容完全一致:

0.000000 LE
2.500000 LE
5.000000 LE
7.500000 LE
10.000000 LE

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:09:01