简体   繁体   English

如何将类似数据的数组从字符串转换为二维数组?

[英]How to convert array like data from a string and to a 2d array?

I am loading the data from an xml file with a structure like: 我正在从具有如下结构的xml文件加载数据:

<project name = "xxx">
    <Parameter name = "yyy">
        <data> <![CDATA[{ { 1, 1, 1, 1}, { 2, 2, 2, 2}, { 3, 3, 3, 3} }]]></data>
    </Parameter>
</project>

I am able to find the data and extract it from xml, but it's in string form along with all the brackets 我能够找到数据并从xml中提取数据,但是它是字符串形式以及所有括号

data = "{ { 1, 1, 1, 1}, { 2, 2, 2, 2}, { 3, 3, 3, 3} }"

I would like to convert it to a 2d array of numbers. 我想将其转换为二维数组。 At this point I use a code that looks like this: 此时,我使用如下代码:

data2d = data.replace('{','[')
data2d = data2d.replace('}',']')
exec('a = np.array('+ data2d +')')

From that code I get what I want: 从该代码中,我得到了我想要的:

a = [[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]]

But I was wondering is there a better way to do that. 但是我想知道是否有更好的方法可以做到这一点。 I really don't like the exec() approach. 我真的不喜欢exec()方法。 Does anyone have any other idea? 还有其他想法吗?

You can use ast.literal_eval : 您可以使用ast.literal_eval

from ast import literal_eval

data = "{ { 1, 1, 1, 1}, { 2, 2, 2, 2}, { 3, 3, 3, 3} }"

lst = literal_eval(data.replace("{", "[").replace("}", "]"))

print(lst, type(lst))
# [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] <class 'list'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM