欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python数据结构之Array用法实例

程序员文章站 2023-12-12 09:01:28
本文实例讲述了python数据结构之array用法,分享给大家供大家参考。具体方法如下: import ctypes class array:...

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

上一篇:

下一篇: