Example of an array usage for Python data structures

Source: Internet
Author: User
This article describes the Python data structure of the array usage, share to everyone for your reference. Here's how:

Import cTYPES class Array:def __init__ (self, size): Assert size > 0, "Array size must is > 0" self._siz E = Size Pyarraytype = ctypes.py_object * Size self._elements = Pyarraytype () self.clear (None) def clear (SE LF, value): For index in range (len): 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 <= si Ze "return self._elements[index" Def __setitem__ (self, Index, value): Assert index >= 0 and Index < Len (s ELF), "Index must >=0 and <= size" self._elements[index] = value def __iter__ (self): return _arrayiterato R (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._cu RNDr + = 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 = nd Xtuple[1] Assert row>=0 and row
 
  
   =0 and col 
   
    = 0 and Row < len (self.numrows) \ and Col >= 0 and Col < Len (self.numcols), \ "R     ow and Col is invalidate "thearray = Self._therows[row]; Thearray[col] = value
    

  
 

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.