如何创建动态数组 [英] How to create a dynamic array

查看:124
本文介绍了如何创建动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,Python中的list类型是动态指针数组,当将项目附加到其上时,它将增加其容量. NumPy中的数组使用连续的内存区域来保存数组的所有数据.

As I understand, the list type in Python is a dynamic pointer array, which will increase it's capacity when items are appended to it. And an array in NumPy uses a continuous memory area to hold all the data of the array.

是否有任何类型可以动态增加其作为列表的容量,并将值存储为NumPy数组?类似于C#中的List.而且,如果类型具有与NumPy数组相同的接口,那就太好了.

Are there any types that dynamically increase its capacity as a list, and stores the value as a NumPy array? Something like List in C#. And it's great if the type has the same interface as a NumPy array.

我可以创建一个将NumPy数组包装在其中的类,并在该数组已满时调整其大小,例如:

I can create a class which wraps a NumPy array inside, and resize this array when it's full, such as:

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

但是DynamicArray不能用作NumPy数组,我认为get_data()在np.resize()之前返回的所有视图都将保留旧数组.

but DynamicArray can't be used as a NumPy array, and I think all the views returned by get_data() before np.resize() will hold the old array.

数组模块中的数组类型为动态数组.以下程序测试列表和数组的增加因子:

array type in array module is dynamic array. The following program test the increase factor of 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()

从图中:list的增加因子大于array.

from the graph: the increase factor of list is bigger than array.

推荐答案

您可能想知道Python标准库还包含

You may be interested to know that the Python standard library also includes an array module which sounds like just what you want:

此模块定义了一个对象类型,该对象类型可以紧凑地表示 基本值数组:字符,整数,浮点数. 数组是序列类型,其行为与列表非常相似,除了 存储在其中的对象的类型受到限制.

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.

这篇关于如何创建动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆