发布于 2014-10-13 02:55:24 | 140 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python入门,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文为大家讲解的是Python中数据结构-Array用法,较为详细的讲述了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 

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务