Python動態陣列的實現
動態陣列
在Python中,列表、集合和字典是可變物件。而數字、字串和元組是不可變物件。可變物件意味著我們可以向列表、集合或字典中新增/刪除項,但對於不可變物件(如元組或字串)則不行。
在Python中,列表就是一個動態陣列。讓我們嘗試建立一個動態列表:
>>> #Create an empty list, named list1 >>> list1 = [] >>> type (list1) <class 'list'>
向我們的空列表list1中新增一些項:
>>> # 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']從列表中刪除一些項:
>>> # deleting item from a list >>> list1.pop() 'Tutorialspoint' >>> list1 [2, 4, 6]
從上面我們可以看出,列表實際上是陣列的擴充套件,我們可以修改(增加或減少)列表的大小。我們從大小為“零”的列表開始,然後向其中添加了“四個”項。
動態陣列實現的基礎
考慮一個例子,當陣列大小已滿時,列表(例如list1)被追加,那麼我們需要執行以下步驟來克服其大小限制的缺點。這是動態陣列實現背後的基礎:
- 分配一個具有更大容量的新陣列list2。
- 設定list2[i] = list1[i],其中i = 0,1,…n-1,n是當前項的數量。
- 設定list1=list2,因為現在list2引用了我們的新列表。
- 然後,只需將新項插入(追加)到我們的列表(list1)中。
讓我們建立一個簡單的程式碼來說明如何在Python程式設計中實現動態陣列的概念。我們將使用Python內建的庫類`ctypes`來建立我們自己的動態陣列類,它將用作`ctypes`模組中的原始陣列。
dynamicArray.py
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()我們的動態類準備好使用後,讓我們嘗試一下:
>>> 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中是列表)的大小。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP