Python3 将字符串转换为 NumPy 数组
Python3 将字符串转换为 NumPy 数组
当您需要将存储为字符串的 NumPy 数组数据重新转换为 NumPy 数组时,可以使用 eval() 函数。
例如,您可能有一个名为 descriptors_str 的字符串,它包含一个用逗号分隔的数字列表,您想将其转换为 NumPy 数组。
import numpy as np
descriptors_str = '[1, 2, 3, 4, 5]'
descriptors = eval(descriptors_str)
descriptors_np = np.array(descriptors)
print(descriptors_np)
输出:
[1 2 3 4 5]
注意: 使用 eval() 函数将字符串转换为代码存在潜在的安全风险。确保您信任字符串的来源,以避免执行恶意代码。
如果您需要更安全的解决方案,可以考虑使用其他方法,例如使用 ast.literal_eval() 函数,它只能解析 Python 字面量,例如数字、字符串和列表。
import ast
import numpy as np
descriptors_str = '[1, 2, 3, 4, 5]'
descriptors = ast.literal_eval(descriptors_str)
descriptors_np = np.array(descriptors)
print(descriptors_np)
这将提供与 eval() 相同的结果,但安全性更高。
原文地址: https://www.cveoy.top/t/topic/qrsx 著作权归作者所有。请勿转载和采集!