python创建数组类_在python中从2D数组类创建一个对象

目前我正在使用python进行数据结构课程。在本书中,他们包含了两个不同的类来实现一维数组结构和二维数组。

对于1D阵列: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 len(self):

return self._size

def getitem(self, index):

assert index >= 0 and index < self.len(), "Array subscript out of range"

return self._elements[index]

def setitem(self, index, value):

assert 0 <= index < self.len(), "Array subscript out of range"

self._elements[index] = value

def clear(self, value):

for i in range(self.len()):

self._elements[i] = value

def iter(self):

return ArrayIterator(self._elements )

class ArrayIterator:

def __init__(self, theArray):

self._arrayRef = theArray

self._curNdx = 0

def __iter__(self):

return self

def __next__(self):

if self._curNdx < len(self._arrayRef):

entry = self._arrayRef[self._curNdx]

self._curNdx += 1

return entry

else:

raise StopIteration

class Array2D :

def __init__( self, numRows, numCols ):

self._theRows = Array( numRows )

for i in range( numRows ) :

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() ):

row.clear( value )

def __getitem__( self, ndxTuple ):

assert len(ndxTuple) == 2, "Invalid number of array subscripts."

row = ndxTuple[0]

col = ndxTuple[1]

assert row >= 0 and row < self.numRows() \

and col >= 0 and col < self.numCols(), \

"Array subscript out of range."

the1dArray = self._theRows[row]

return the1dArray[col]

def __setitem__( self, ndxTuple, value ):

assert len(ndxTuple) == 2, "Invalid number of array subscripts."

row = ndxTuple[0]

col = ndxTuple[1]

assert row >= 0 and row < self.numRows() \

and col >= 0 and col < self.numCols(), \

"Array subscript out of range."

the1dArray = self._theRows[row]

the1dArray[col] = value

我使用以下代码来了解它是如何工作的:arr = Array(5)

arrLen = arr.len()

arr.clear(0)

for i in range (arrLen):

print arr.getitem(i)

print "The length of the array = ",arrLen

print "Enter 5 numbers"

for i in range (arrLen):

#n = raw_input("num = ")

arr.setitem(i,i)

for i in range (arrLen):

print arr.getitem(i)

print"values are ", arr.iter()

但是,我不知道如何调用2D数组来理解它是如何工作的。ArrMulti = Array2D(3, 4)

我收到以下错误:File "MultiArrayADT.py", line 46, in __init__

self._theRows[i] = Array( numCols )

AttributeError: Array instance has no attribute '__setitem__'

所以请告诉我如何创建2D数组对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值