简体   繁体   中英

Efficient way of extracting from an array of objects

I have a an array of objects in python:

meshnodearray = ['MeshNode object', 'MeshNode object', 'MeshNode object', ...]

Where for example first 'MeshNode object' is:

({'coordinates': (15.08, 273.01, 322.61), 'instanceName': None, 'label': 1})

I need to create an array of coordinates like this:

NODEcoo = np.zeros((nnod,3),dtype='float64')
for i in meshnodearray:
    NODEcoo[i.label-1,0:] = np.array(i.coordinates)

For large arrays this is slow. Is there a more efficient way of doing this, maybe without the for loop?

Try extracting the coordinates into a python list of coordinates and converting it into a numpy array in one go. If the label values are sequential from 1 to nnod , it's as simple as this:

coords = [ n['coordinates'] for n in meshnodearray ]
NODEcoo = np.array(coords)

It would be somewhat better to do this with a generator (which would let you avoid creating the intermediate array), but numpy can create only one-dimensional arrays from a generator, with numpy.fromiter() .

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