数组Array
数组Array是最基本的数据结构,在内存中为一段定长连续内存,很多编程语言都有实现。
一、一维数组
下面代码实现了一维数组和它的遍历。
clear并非清空数组,而是采用具体值对数组进行初始化。
import ctypes class Array : def __init__( self, size ): assert size > 0, "Array size must be > 0" self._size = size PyArrayType = ctypes.py_object * size self._elements = PyArrayType() self.clear( None ) def __len__( self ): return self._size def __getitem__( self, index ): assert index >=0 and index < len(self), "Array subscript out of range" return self._elements[ index ] def __setitem__( self, index, value ): assert index >=0 and index < len(self), "Array subscript out of range" self._elements[ index ] = value def clear( self, value ): for i in range( len(self) ) : self._elements[i] = value def __iter__( self ): return _ArrayIterator( self._elements )
class _ArrayIterator : def __init__( self, theArray ): self._arrayRef = theArray self._curNdx = 0 def __iter__( self ): return self def __next__( self ): if self._curNdx < len( self._arrayRef ) : entry = self._arrayRef[ self._curNdx ] self._curNdx += 1 return entry else : raise StopIteration if __name__=='__main__': myarray=Array(5) myarray.clear(1) myarray.__setitem__(2,5) print myarray.__getitem__(2) it=myarray.__iter__() while True: try: print it.__next__() except StopIteration: break
二、二维数组
二维数组的构造基于一维数组Array,它可以看做是一个以行数为size的一维数组,区别在于数组中的每个元素并不是具体的值,而是由以列数为size的数组构成。如下图所示:
class Array2D : def __init__( self, numRows, numCols ): self._theRows = Array( numRows ) for i in range( numRows ) : self._theRows[i] = Array( numCols ) def numRows( self ): return len( self._theRows ) def numCols( self ): return len( self._theRows[0] ) def __getitem__( self, ndxTuple ): assert len(ndxTuple) == 2, "Invalid number of array subscripts." row = ndxTuple[0] col = ndxTuple[1] assert row >=0 and row < self.numRows() and col >=0 and col < self.numCols(), "Array subscript out of range." the1dArray = self._theRows[row] return the1dArray[col] def __setitem__( self, ndxTuple, value ): assert len(ndxTuple) == 2, "Invalid number of array subscripts." row = ndxTuple[0] col = ndxTuple[1] assert row >=0 and row < self.numRows() and col >=0 and col < self.numCols(), "Array subscript out of range." the1dArray = self._theRows[row] the1dArray[col] = value
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗