python學習3--python複雜資料類型

來源:互聯網
上載者:User

標籤:heap   deque   random   shuf   mod   堆棧   dom   複雜   rgb   


1 堆

堆是一種二叉樹,其中每個父節點的值都小於或等於其所有子節點的值,最小的元素總是位於二叉樹的根節點。

堆的建立

import heapqimport randomdata = range(10)random.shuffle(data) #打亂順序heap = [] for n in data:     heapq.heappush(heap,n) print heapheapq.heappushpop(heap,0.5) #新資料入堆heapq.heappop(heap) #彈出最小的元素,堆重建

列錶轉化為堆

myheap = [100,2,3,4,22,7,10,5]heapq.heapify(myheap) #將列錶轉化為堆heapq.heapreplace(myheap,6) #替代堆棧元素值,堆重建heapq.nlargest(3,myheap) #返回最大的3個值heapq.nsmallest(3,myheap) #最小3個

2 隊列

隊列的特點是First in first out, last in last out,先進先出,後進後出

import Queueq = Queue.Queue() q.put(0) #元素入隊q.put(1) q.put(2) print q.queue #deque([0, 1, 2]) print q.get() #元素0先出隊print q.queue() #deque([1, 2])


3 棧

棧的特點是Last in last out,first in last out,後進先出,先進後出

list 就可以實現棧的基本操作,append()相當於入棧,pop()相當於出棧,但是當列表為空白時pop()操作會有異常,也無法限制棧的大小。

import Stackx = Stack.Stack()x.push(1)x. push(2)x.show()x.pop()x.show()
class Stack:     def __init__(self, size=10):         self._content = []         self._size = size     def empty(self):         self._content = []     def isEmpty(self):         if not self._content:             return True         else:             return False     def setSize(self,size):         self._size = size     def isFull(self):         if len(self._content)==self._size:             return True         else:             return False     def push(self,v):         if len(self._content)<self._size:             self._content.append(v)         else:             print ‘Stack Full‘     def pop(self):         if self._content:             return self._content.pop()         else:             print ‘Stack is empty!‘     def show(self):         print self._content     def showRemainderSpace(self):         print ‘Stack can still PUSH‘,self.size-len(self._content),‘elements.‘     if __name__==‘__main__‘:         print ‘Please use me as a module‘

4 鏈表

可以直接使用list及其基本操作實現鏈表的功能

linkTable = []linkTable.append(3)linkTable.append(5)linkTable.insert(1,4)linkTable.remove(linkTable[1])


5 二叉樹

6 有向圖






python學習3--python複雜資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.