数组Array
2024-09-30 11:55:19
数组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
最新文章
- 使用外部web组件-----easyUI、jQueryUI、Bootstrap、js正则表达式
- SQL Server中CROSS APPLY和OUTER APPLY的应用详解
- 搭建Cordova开发环境
- jQuery之on
- android webview远程调试
- 对Object类中方法的深入理解
- 【风马一族_git_github】github项目建成网站
- laravel homestead
- 如何禁止掉SharePoint页面个性化(网站操作-编辑页面)
- Linux创建新用户以及useradd adduser的区别
- Java基础知识强化之集合框架笔记54:Map集合之HashMap集合(HashMap<;String,String>;)的案例
- Android性能优化典范【转】
- jquery 分页控件2
- 有关数据传输GET和POST的方法的区别
- C#之FileInfo的简单操作
- HDFS的dfs.replication不同验证
- 读写锁--DEMO
- Deck of Cards ZOJ - 2852 dp 多决策 三维 滚动更新
- Machine.config与web.config
- curl命令整理