时间:2021-05-22
本文实例讲述了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程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了Python学习笔记基本数据结构之序列类型listtuplerange用法。分享给大家供大家参考,具体如下:list和tuplelist:列表,由
数据结构之数组Array实例详解数组Array基本操作StatusInitArray(intdimm,...)//若维数dim和随后的各维长度合法,则构造相应的
本文实例讲述了Python基本语法之运算符功能与用法。分享给大家供大家参考,具体如下:前言在前面的博文介绍了Python的数据结构之后,接下来结合Python操
本文实例讲述了Python基本数据结构之字典类型dict用法。分享给大家供大家参考,具体如下:词典类型dict字典由键(key)和对应值(value)成对组成。
本文实例讲述了Python数据结构之图的应用。分享给大家供大家参考,具体如下:一、图的结构二、代码#-*-coding:utf-8-*-#!python3def