Python数据结构之Array用法实例

yipeiwu_com5年前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程序设计有所帮助。

相关文章

python 生成不重复的随机数的代码

复制代码 代码如下: import random print 'N must >K else error' n=int(raw_input("n=")) k=int(raw_inp...

如何使用Flask-Migrate拓展数据库表结构

前言 在我们用 sqlchemy 模块创建完几个表时,如果在实际生产环境中,需要对表结构进行更改,应该怎么办呢?总不能把表删除了吧,这样数据就会丢失了。 更好的解决办法是使用数据库迁移框...

python Pandas 读取txt表格的实例

运行环境 Python 2.7 操作实例 1.原始文本格式:空格分隔的txt,例如 2016-03-22 00:06:24.4463094 中文测试字符 2016-03-22 00...

python利用高阶函数实现剪枝函数

本文为大家分享了python利用高阶函数实现剪枝函数的具体代码,供大家参考,具体内容如下 案例:        某些时候,我们...

Android 兼容性问题:java.lang.UnsupportedOperationException解决办法

Android 兼容性问题:java.lang.UnsupportedOperationException解决办法

在前几天的开发中,遇到这么个非常奇葩的异常,有些手机可以运行,有些手机却直接就崩了,今天就把这异常整理下。 首先还是贴上其异常信息 E/AndroidRuntime: FATAL E...