动态数组在Python中的实现

Implementation of Dynamic Array in Python

动态阵列

在python中,列表,集合和字典是可变对象。数字,字符串和元组是不可变的对象。可变对象意味着我们从列表,集合或字典中添加/删除项目,但是对于不可变对象(例如元组或字符串)而言,情况并非如此。

在python中,列表是一个动态数组。让我们尝试创建一个动态列表-

1
2
3
4
>>> #Create an empty list, named list1
>>> list1 = []
>>> type (list1)
<class 'list'>

将一些项目添加到我们的空列表list1-

1
2
3
4
5
6
7
8
>>> # Add items
>>> list1 =[2, 4, 6]
>>> list1
[2, 4, 6]
>>> # Another way to add items, using append.
>>> list1.append('Tutorialspoint')
>>> list1
[2, 4, 6, 'Tutorialspoint']

从列表中删除一些项目-

1
2
3
4
5
>>> # deleting item from a list
>>> list1.pop()
'Tutorialspoint'
>>> list1
[2, 4, 6]

从上方我们可以看到列表实际上是数组的扩展,在这里我们可以修改(增加或减少)列表的大小。我们从大小为"零"的列表开始,然后向其中添加"四个"项目。

动态数组实现的基础

考虑一个例子,其中的列表。当数组的大小已满时,将添加list1,然后,我们需要执行以下步骤来克服其大小限制的缺点。这是动态数组实现的基础-

  • 分配具有更大容量的新阵列列表2
  • 设置list2 [i] = list1 [i],因为i = 0,1….n-1,其中n是该项目的当前编号。
  • 设置list1 = list2,因为现在list2正在引用我们的新列表。
  • 然后,只需将新项目插入(添加)到我们的列表(列表1)即可。

让我们为如何在python编程中实现动态数组概念创建一个简单的代码。我们将使用python中称为ctypes的内置库类来创建自己的动态数组类,该类将用作ctypes模块中的原始数组。

dynamicArray.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import ctypes
class DynamicArray(object):
 #Initialize it
 def __init__(self):
   #We'll have three attributes
   self.n = 0 # by default
   self.capacity = 1 # by default
   self.A = self.make_array(self.capacity) # make_array will be defined later
 #Length method
 def __len__(self):
   #It will return number of elements in the array
   return self.n
 def __getitem__(self, k):
   #it will return the elements at the index k
 if not 0 <=k <self.n:
   return IndexError('k is out of bounds')
 return self.A[k]
 def append(self, element):
 #checking the capacity
 if self.n == self.capacity:
   #double the capacity for the new array i.e
   self.resize(2*self.capacity) # _resize is the method that is defined later
 # set the n indexes of array A to elements
 self.A[self.n] = element
 self.n += 1
 def _resize(self, new_cap): #new_cap is for new capacity
 #declare array B
 B = self.make_array(new_cap)
 for k in range(self.n):
   B[k] = self.A[k] # referencing the elements from array A to B
   #ones refered then
 self.A = B # A is now the array B
 self.capacity = new_cap # resets the capacity
 #making the make-array method using ctypes
 def make_array(self,new_cap):
   return (new_cap * ctypes.py_object)()
arr = DynamicArray()

当我们准备使用动态类时,请尝试使用它-

1
2
3
4
5
6
7
8
9
10
11
12
>>> len(arr)
0
>>> arr.append(1)
>>> #First item entered
>>> len(arr)
1
>>> arr.append('Tutorialspoint')
>>> #second item entered
>>> len(arr)
2
>>> arr[1]
'Tutorialspoint'

就是这样,我们已经创建了自己的动态数组,并且可以调整数组的大小,该数组是python中的列表。