How to create a dynamic array

As I understand it, the list type in Python is a dynamic array of pointers, which increases its capacity when adding elements to it. And the array in NumPy uses a continuous memory area to store all the data in the array.

Are there types that dynamically increase its capacity as a list and store the value as a NumPy array? Something like List in C #. And this is great if the type has the same interface as the NumPy array.

I can create a class that wraps a NumPy array inside and resizes the array when it is populated, for example:

 class DynamicArray(object): def __init__(self): self._data = np.zeros(100) self._size = 0 def get_data(self): return self._data[:self._size] def append(self, value): if len(self._data) == self._size: self._data = np.resize(self._data, int(len(self._data)*1.25)) self._data[self._size] = value self._size += 1 

but DynamicArray cannot be used as a NumPy array, and I think that all views returned by get_data () before np.resize () will contain the old array.

Edit: the type of the array in the array is a dynamic array. The following program checks the magnification factor of the list and array:

 from array import array import time import numpy as np import pylab as pl def test_time(func): arrs = [func() for i in xrange(2000)] t = [] for i in xrange(2000): start = time.clock() for a in arrs: a.append(i) t.append(time.clock()-start) return np.array(t) t_list = test_time(lambda:[]) t_array = test_time(lambda:array("d")) pl.subplot(211) pl.plot(t_list, label="list") pl.plot(t_array, label="array") pl.legend() pl.subplot(212) pl.plot(np.where(t_list>2*np.median(t_list))[0]) pl.plot(np.where(t_array>2*np.median(t_array))[0]) pl.show() 

enter image description here

from the graph: the list enlargement coefficient is larger than the array.

+13
python list numpy
Aug 05 2018-11-18T00:
source share
1 answer

You may be interested to know that the standard Python library also includes an array module, which sounds exactly the way you want:

This module determines the type of object that can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are types of sequences and are very similar to lists, except that the type of objects stored in them is limited.

+13
Aug 05 2018-11-11T00:
source share



All Articles