Python数据结构之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程序设计有所帮助。

(0)

相关推荐

  • python中二维阵列的变换实例

    本文实例讲述了python中二维阵列的变换方法.分享给大家供大家参考.具体方法如下: 先看如下代码: arr = [ [1, 2, 3], [4, 5, 6], [7, 8,9], [10, 11, 12]] print map(list, zip(*arr)) print '_-------------------------------------------------' print [[r[col] for r in arr] for col in range(len(arr[0]))]

  • python实现简单的TCP代理服务器

    本文实例讲述了python实现简单的TCP代理服务器的方法,分享给大家供大家参考. 具体实现代码如下: # -*- coding: utf-8 -*- ''' filename:rtcp.py @desc: 利用python的socket端口转发,用于远程维护 如果连接不到远程,会sleep 36s,最多尝试200(即两小时) @usage: ./rtcp.py stream1 stream2 stream为:l:port或c:host:port l:port表示监听指定的本地端口 c:host

  • python中pygame模块用法实例

    本文实例讲述了python中pygame模块用法,分享给大家供大家参考.具体方法如下: import pygame, sys from pygame.locals import * #set up pygame pygame.init() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("hello, world") BLACK = (0, 0, 0) WHITE

  • python批量提交沙箱问题实例

    本文实例讲述了python批量提交沙箱问题,分享给大家供大家参考.具体方法如下: 出现的问题如下: 1. Popen的使用,在linux下参数用列表传,不要用字符串传   否则可能会有"OSErrorror: [Errno 2] No such file or directory"错误 2. 列表要拷贝用 shutil模块中  不然会连续append..提交完第一个样本后,后面的提交参数就错了. 代码如下: import os from subprocess import Popen

  • python命令行参数解析OptionParser类用法实例

    本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下: from optparse import OptionParser parser = OptionParser(usage="usage:%prog [optinos] filepath") parser.add_option("-t", "--timeout", action = "store", type =

  • python根据文件大小打log日志

    本文实例讲述了python根据文件大小打log日志的方法,分享给大家供大家参考.具体方法如下: import glob import logging import logging.handlers LOG_FILENAME='logging_rotatingfile_example.out' # Set up a specific logger with our desired output level my_logger = logging.getLogger('MyLogger') my_l

  • python实现每次处理一个字符的三种方法

    本文实例讲述了python每次处理一个字符的三种方法.分享给大家供大家参考. 具体方法如下: a_string = "abccdea" print 'the first' for c in a_string: print ord(c)+1 print "the second" result = [ord(c)+1 for c in a_string] print result print "the thrid" def do_something(

  • python操作CouchDB的方法

    本文简单讲述了python操作CouchDB的方法,分享给大家供大家参考.具体方法如下: 1.安装python couchDb库: https://pypi.python.org/pypi/CouchDB/0.10 2.连接服务器 >>> import couchdb >>> couch = couchdb.Server('http://example.com:5984/') 3.创建数据库 >>> db = couch.create('test')

  • python测试驱动开发实例

    本文实例讲述了python测试驱动开发的方法,分享给大家供大家参考.具体方法如下: import unittest from main import Sample class SampleTest(unittest.TestCase): def setUp(self): print "create a new Sample" self._sample = Sample("b64e5843ca7db8199c405be565fa7f57") def tearDown(

  • python求pi的方法

    本文实例讲述了python求pi的方法,是一篇翻译自国外网站的文章,分享给大家供大家参考. 具体实现方法如下: #_*_ coding=utf-8 *_* ## {{{ http://code.activestate.com/recipes/578130/ (r5) def pi(places=10): """Computes pi to given number of decimal places 参数places表示要返回的pi的小数点后位数 方法:先整体扩大10**8(

  • Python正则表达式匹配ip地址实例

    本文实例讲述了正则表达式匹配ip地址实例.代码结构非常简单易懂.分享给大家供大家参考. 主要实现代码如下: import re reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])') for ip in reip.findall(line): print "ip>>>", ip PS:关于正则,这里再为大家推荐2款非常方便的正则表达式工具供大家参考使用: JavaScript正则表达式

  • python基于queue和threading实现多线程下载实例

    本文实例讲述了python基于queue和threading实现多线程下载的方法,分享给大家供大家参考.具体方法如下: 主代码如下: #download worker queue_download = Queue.Queue(0) DOWNLOAD_WORKERS = 20 for i in range(DOWNLOAD_WORKERS): DownloadWorker(queue_download).start() #start a download worker for md5 in MD5

随机推荐