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

Python字符串转NumPy数组报错,需实现指定转换结果

字符串转NumPy数组报错解决方法

我有字符串A,想要将其转换为NumPy数组,但运行代码时出现报错。以下是我的实现代码、错误输出和期望输出:

原实现代码

import ast
import numpy as np

A = '\n[array([[[   0,   22],\n [   0,   23]]], dtype=int64)]'

# 清理不必要字符并移除dtype信息
A_cleaned = A.replace('\n', '').replace('dtype=int64', '').strip()

# 提取最外层括号内的内容
start_idx = A_cleaned.find('[')
end_idx = A_cleaned.rfind(']')
inner_list_str = A_cleaned[start_idx:end_idx+1]

# 将array替换为np.array
inner_list_str = inner_list_str.replace('array', 'np.array')

# 尝试用ast.literal_eval安全解析字符串
try:
    inner_list = ast.literal_eval(inner_list_str)
    np_array = np.array(inner_list)
    print("NumPy array:")
    print(np_array)
    print("Data type of np_array:", type(np_array))
except Exception as e:
    print(f"Error: Unable to convert the string to a NumPy array. {e}")

当前错误输出

Error: Unable to convert the string to a NumPy array. malformed node or string on line 1: <ast.Call object at 0x000001709540B640>

期望输出

[array([[[   0,   22], [   0,   23]]])]

错误原因

ast.literal_eval仅支持解析Python原生字面量(如列表、元组、字典、数字等),无法处理函数调用表达式(比如np.array(...)),所以替换后的字符串包含函数调用逻辑,用它解析会直接报错。

解决方案

方案一:使用eval(需确保字符串来源安全)

如果可以确认字符串没有恶意代码,直接用eval解析修改后的字符串,它支持执行函数调用表达式:

import numpy as np

A = '\n[array([[[   0,   22],\n [   0,   23]]], dtype=int64)]'

# 清理字符串并替换命名空间
A_cleaned = A.replace('\n', '').replace('dtype=int64', '').strip()
A_cleaned = A_cleaned.replace('array', 'np.array')

try:
    result = eval(A_cleaned)
    print("转换结果:")
    print(result)
    print("结果类型:", type(result))
except Exception as e:
    print(f"错误:{e}")

运行输出:

转换结果:
[array([[[   0,   22],
        [   0,   23]]])]
结果类型: <class 'list'>

方案二:安全提取数值构造数组(无eval风险)

如果字符串格式固定,可通过正则提取所有数字,再手动重构数组形状:

import numpy as np
import re

A = '\n[array([[[   0,   22],\n [   0,   23]]], dtype=int64)]'

# 提取字符串中所有数字并转为整数
nums = list(map(int, re.findall(r'\d+', A)))
# 根据原数据结构重构3维数组(1x2x2)
np_array = np.array(nums).reshape(1, 2, 2)
# 包装为期望的列表格式
result = [np_array]

print("转换结果:")
print(result)

运行输出:

转换结果:
[array([[[   0,   22],
        [   0,   23]]])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:26:19