如何在Python中将字符串(描述数组)转换为数组

时间:2018-11-05 09:40:56

标签: python string python-3.x numpy

我有这个字符串:

'[[57.7322273254, -58.8288497925, -54.460193634, 28.4842605591, -45.9620323181, -13.6266260147, -17.2981243134, -15.1332969666, -15.1287126541, -2.44765377045, -0.488036692142, -9.05566310883, -4.70651531219], [72.5999526978, -83.4902877808, -16.4493045807, 40.4356307983, -33.9553756714, -10.7394323349, -17.31067276, -15.6521835327, -25.1421508789, -13.1496963501, -4.11457395554, -14.9144859314, -5.76139545441]]'

我想将此字符串转换为数组的numpy数组

1 个答案:

答案 0 :(得分:0)

import ast

print(ast.literal_eval('[[57.7322273254, -58.8288497925, -54.460193634, 28.4842605591, -45.9620323181, -13.6266260147, -17.2981243134, -15.1332969666, -15.1287126541, -2.44765377045, -0.488036692142, -9.05566310883, -4.70651531219], [72.5999526978, -83.4902877808, -16.4493045807, 40.4356307983, -33.9553756714, -10.7394323349, -17.31067276, -15.6521835327, -25.1421508789, -13.1496963501, -4.11457395554, -14.9144859314, -5.76139545441]]'))

这将使此字符串成为列表。

您可以使用np.array对其进行强制转换,以使其成为一个numpy数组。

在此处阅读有关ast.literal_eval

的信息
  

安全地评估表达式节点或Unicode或Latin-1编码   包含Python文字或容器显示的字符串。字符串或   提供的节点只能由以下Python文字组成   结构:字符串,数字,元组,列表,字典,布尔值和   没有。