Python数据结构之Array用法实例,pythonarray
Python数据结构之Array用法实例,pythonarray
本文实例讲述了python数据结构之Array用法,分享给大家供大家参考。具体方法如下:
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 clear(self, value): for index in range(len(self)): self._elements[index] = value def __len__(self): return self._size def __getitem__(self, index): assert index >= 0 and index < len(self), "index must >=0 and <= size" return self._elements[index] def __setitem__(self, index, value): assert index >= 0 and index < len(self), "index must >=0 and <= size" self._elements[index] = value def __iter__(self): return _ArrayIterator(self._elements) class _ArrayIterator: def __init__(self, theArray): self._arrayRef = theArray self._curNdr = 0 def __next__(self): if self._curNdr < len(theArray): entry = self._arrayRef[self._curNdr] sllf._curNdr += 1 return entry else: raise StopIteration def __iter__(self): return self
class Array2D : def __init__(self, numRows, numCols): self._theRows = Array(numCols) for i in range(numCols): self._theRows[i] = Array(numCols) def numRows(self): return len(self._theRows) def numCols(self): return len(self._theRows[0]) def clear(self, value): for row in range(self.numRows): self._theRows[row].clear(value) def __getitem__(self, ndxTuple): assert len(ndxTuple) == 2, "the tuple must 2" row = ndxTuple[0] col = ndxTuple[1] assert row>=0 and row <len(self.numRows()) \ and col>=0 and col<len(self.numCols), \ "array subscrpt out of range" theArray = self._theRows[row] return theArray[col] def __setitem__(self, ndxTuple, value): assert len(ndxTuple)==2, "the tuple must 2" row = ndxTuple[0] col = ndxTuple[1] assert row >= 0 and row < len(self.numRows) \ and col >= 0 and col < len(self.numCols), \ "row and col is invalidate" theArray = self._theRows[row]; theArray[col] = value
希望本文所述对大家的Python程序设计有所帮助。
Python数据结构1. 列表list:变量赋值方式:shoplist=['apple','mango','carrot','banana']2. 元组array:变量赋值方式:zoo=(‘wolf’,‘elephant’,'penguin’)3. 字典dict:变量赋值方式:d={key1:value1,key2:value2}4. 序列:列表、元组和字符串都是序列(1) 索引操作符:取得列表/元组中的一个元素或字符串的的某个字符(2) 切片操作符:取得序列的一个切片,连续的元素/字符(3) eg:name=’swaroop’print‘characters0is’,name[0]#’s’索引操作符,类似C#print‘characters1to3is’,name[1:3]‘wa’ 切片操作符,类似C# 中的Substring方法事实上Python包含的内容还很多很多,如Python和传统的解释型脚本语言不同,它在第一次执行时会编译成字节码,其后执行就直接运行字 节码了,这个.NET的DLR有点类似源码天空,和Java的虚拟机也类似,总之是将代码转化成更接近机器代码的方式,这样可以提高性能。
等价代码
a = [1, 2, 3]
for i in a:
print i
评论关闭