简体   繁体   中英

Python - How to construct a numpy array out of a list of objects efficiently

I am building a python application where I retrieve a list of objects and I want to plot them (for ploting I use matplotlib ). Each object in the list contains two properties.

For example let's say I have the list rawdata and the objects stored in it have the properties timestamp and power

rawdata[0].timestamp == 1
rawdata[1].timestamp == 2
rawdata[2].timestamp == 3

etc

rawdata[0].power == 1232.547
rawdata[1].power == 2525.423
rawdata[2].power == 1125.253

etc

I want to be able to plot those two dimensions, that the two properties represent, and I want to do it a time and space efficient way. That means that I want to avoid iterating over the list and sequentially constructing something like a numpy array out it.

Is there a way that to apply an on-the-fly transformation of the list? Or somehow plot it as it is? Since all the information is already included in the list I believe there should be a way.

The closest answer I found was this , but it includes sequential iteration over the list.

update

As pointed out by Antonio Ragagnin I can use the map builtin function to construct a numpy array efficiently. But that also means that I will have to create a second data structure. Can I use map to transform the list on the fly to a two dimensional numpy array?

From the matplotlib tutorial (emphasis mine):

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally.

So you lose nothing by converting it to a numpy array, if you don't do it matplotlib will.

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