一、數組python
Python中使用最多的數據結構之一就是數組列表,是一種包含一系列有序對象的對象。能夠經過數值索引來對其進行訪問,第一個(或最左邊)對象的索引爲0。Python也支持負值索引,最後一個對象索引爲-1,向左依次遞減。數組
列表方法:a=[4,3,4,56,6,3e],len(a)返回列表的列表長度(對象個數);Python會在程序運行中對索引的有效性進行檢查,有效值爲 -n 到 n-1 ,n爲列表長度。a.reverse() 列表逆序。數據結構
數組類的重定義:spa
class Array(object): #數組初始化方法 def __init__(self,length =0,baseIndex = 0): assert length >= 0 self.data =[None for i in xrange(length)] self.baseIndex = baseIndex #定義數組的拷貝方法(淺拷貝),複製以後副本數組內的元素對象和本來數組的元素對象是同一個。 def __copy__(self): result = Array(len(self._data)) for i,datum in enumerate(self._data): result._data[i] = datum result.baseIndex = self.baseIndex return result #定義和存儲訪問數組對象的方法 def getOffset(self,index): offset = index - self.baseIndex if offset < 0 or offset >= len(self._data): raise IndexError def __getitem__(self,index): return self._data[self.getOffset(index)] def __setitem__(self,index,value): self._data[self.getOffset(index)] = value