Python数据结构之Array用法实例

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

定制FileField中的上传文件名称实例

FileField中的upload_to属性可以设定上传文件的存储目录和名称,它可以是个字符串,也可以是个callable,比如一个方法。 当upload_to的值设为一个方法时,就可以...

python3多线程知识点总结

多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人,比如用户点击了一个按钮去触发某些事件的处理,可以...

基于pip install django失败时的解决方法

使用pip安装Django时报错,先是: C:\Users\admin>pip install django Collecting django Retrying (Re...

python递归法解决棋盘分割问题

python递归法解决棋盘分割问题

题目描述:将一个8*8的棋盘进行分割,将原棋盘分割下一个矩阵,同时确保剩下的棋盘也是矩阵; 再将剩下的棋盘继续进行如上分割,这样割(n-1)次,最后原棋盘被分割成n块矩形棋盘; 注意:每...

基于 Django 的手机管理系统实现过程详解

基于 Django 的手机管理系统实现过程详解

一、概述 打算通过设计数据库,然后结合 Python 框架Django,实现在网页上对数据库的增删改查(本例以手机的管理为例,不考虑订购功能),有普通用户界面和管理员用户界面,普通用户只...