简体   繁体   中英

Python analog to MatLab data structure

I've recently jumped out of the matrix laboratory window and I'm trying to get Python/Numpy/Scipy to do the things I used to do in MatLab. It seems really good so far, but one thing I'm struggling with is finding something similar to the data structure in MatLab.

I want to write a general code for reading in an .xml file and automatically assigning variables into a data structure depending on whether they are strings, scalars or matrices. A typical xml file would be split up like this:

<material>
<id>
1
<\id>
<E>
17e4
<\E>
<var 2>
'C:\data file path'
<\var 2>
<var 3>
[1 2;3 4]
<\var 3>
<\material>
<material>
<id>
2
<\id>
<var 1>
17e4
<\var 1>
<var 2>
'C:\data file path'
<\var 2>
<var 3>
[1 2;3 4]
<\var 3>
<\material>
...
etc

In Matlab I would have created a data structure something like this:

Materials.1.E=17e4
Materials.1.var2='C:\data file path'
Materials.1.var3=[1 2;3 4]
Materials.2.E=17e4
Materials.2.var2='C:\data file path'
Materials.2.var3=[1 2;3 4]

If the list in python could be 2D (so I could have all of the variables for each material on one row) or the dictionary could have more than one layer or could contain lists they'd be perfect but I can't find what I want at the moment!

Any help will be much appreciated!

As Shai suggests, you could use a list of dictionaries. For your example this would look something like this:

Materials = []

Materials.append({'E': 17e4, 'var2': 'C:\\data file path', 'var3': [1, 2, 3, 4]})
Materials.append({'E': 17e4, 'var2': 'C:\data file path', 'var3':[1, 2,3, 4]})

print Materials[0]['var2']

which prints:

C:\data file path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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