Python中順序表的實現簡單代碼分享,python順序
順序表python版的實現(部分功能未實現)
結果展示:
程式碼範例:
#!/usr/bin/env python# -*- coding:utf-8 -*-class SeqList(object): def __init__(self, max=8): self.max = max #建立預設為8 self.num = 0 self.date = [None] * self.max #list()會預設建立八個元素大小的列表,num=0,並有連結關係 #用list實現list有些荒謬,全當練習 #self.last = len(self.date) #當列表滿時,擴建的方式省略 def is_empty(self): return self.num is 0 def is_full(self): return self.num is self.max #擷取某個位置的元素 def __getitem__(self, key): if not isinstance(key, int): raise TypeError if 0<= key < self.num: return self.date[key] else: #表為空白或者索引超出範圍都會引發索引錯誤 raise IndexError #設定某個位置的元素 def __setitem__(self, key, value): if not isinstance(key, int): raise TypeError #只能訪問列表裡已有的元素,self.num=0時,一個都不能訪問,self.num=1時,只能訪問0 if 0<= key < self.num: self.date[key] = value #該位置無元素會發生錯誤 else: raise IndexError def clear(self): self.__init__() def count(self): return self.num def __len__(self): return self.num #加入元素的方法 append()和insert() def append(self,value): if self.is_full(): #等下擴建列表 print("list is full") return else: self.date[self.num] = value self.num += 1 def insert(self,key,value): if not isinstance(key, int): raise TypeError if key<0: #暫時不考慮負數索引 raise IndexError #當key大於元素個數時,預設尾部插入 if key>=self.num: self.append(value) else: #移動key後的元素 for i in range(self.num, key, -1): self.date[i] = self.date[i-1] #賦值 self.date[key] = value self.num += 1 #刪除元素的操作 def pop(self,key=-1): if not isinstance(key, int): raise TypeError if self.num-1 < 0: raise IndexError("pop from empty list") elif key == -1: #原來的數還在,但列表不識別他 self.num -= 1 else: for i in range(key,self.num-1): self.date[i] = self.date[i+1] self.num -= 1 def index(self,value,start=0): for i in range(start, self.num): if self.date[i] == value: return i #沒找到 raise ValueError("%d is not in the list" % value) #列表反轉 def reverse(self): i,j = 0, self.num - 1 while i<j: self.date[i], self.date[j] = self.date[j], self.date[i] i,j = i+1, j-1if __name__=="__main__": a = SeqList() print(a.date) #num == 0 print(a.is_empty()) a.append(0) a.append(1) a.append(2) print(a.date) print(a.num) print(a.max) a.insert(1,6) print(a.date) a[1] = 5 print(a.date) print(a.count()) print("傳回值為2(第一次出現)的索引:", a.index(2, 1)) print("====") t = 1 if t: a.pop(1) print(a.date) print(a.num) else: a.pop() print(a.date) print(a.num) print("========") print(len(a)) a.reverse() print(a.date) """ print(a.is_full()) a.clear() print(a.date) print(a.count()) """
有關於Python資料結構中順序表的實現,大家也可以參考本站的另一篇文章《Python資料結構之順序表的實現程式碼範例》 ,當中有對順序表略微詳細的介紹。小編對此知識點理解不夠透徹,以後還會繼續研究的。
以上就是本文關於Python中順序表的實現簡單代碼分享的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!