python 数组 动态赋值_动态数组在Python中的实现

动态数组

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

在python中,列表是一个动态数组。让我们尝试创建一个动态列表->>> #Create an empty list, named list1

>>> list1 = []

>>> type (list1)

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

>>> list1 =[2, 4, 6]

>>> list1

[2, 4, 6]

>>> # Another way to add items, using append.

>>> list1.append('Nhooo')

>>> list1

[2, 4, 6, 'Nhooo']

从列表中删除一些项目->>> # deleting item from a list

>>> list1.pop()

'Nhooo'

>>> list1

[2, 4, 6]

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

动态数组实现的基础

考虑一个示例,其中在数组的大小已满时附加了list .ie list1,然后,我们需要执行以下步骤来克服其大小限制的缺点。这是动态数组实现背后的基础-分配具有更大容量的新数组列表2

设置list2 [i] = list1 [i],因为i = 0,1….n-1,其中n是该项目的当前编号。

设置list1 = list2,因为现在list2正在引用我们的新列表。

然后,只需将新项目插入(添加)到我们的列表(列表1)即可。

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

dynamicArray.pyimport 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 

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('Nhooo')

>>> #second item entered

>>> len(arr)

2

>>> arr[1]

'Nhooo'

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值