python中三种特殊数据结构:set集合、堆、双端队列

来源:互联网 发布:sopcast网络电视安卓版 编辑:程序博客网 时间:2024/06/06 17:12

1set集合:是一个无序不重复元素集

1.>>> x & y # 交集  2.set(['a', 'm'])  3.  4.>>> x | y # 并集  5.set(['a', 'p', 's', 'h', 'm'])  6.  7.>>> x - y # 差集  8.set(['p', 's'])  t和s都为set集合1.t.add('x')            # 添加一项   2.s.update([10,37,42])  # 在s中添加多项  


(2)堆:heapq(在列表上操作,而且默认为小根堆,能够能快的弹出最小值

heappush(heap,x)   #x入堆  

#导入堆模块import heapqheap=[]for n in range(10):    heapq.heappush(heap,n)print heapq.nlargest(3, heap)   #返回topN大的数


(3)双端队列:在需要按照元素增加的顺序来移除元素时有用(deque

#双端队列

from collections import dequeq=deque(range(5))q.append(5)q.appendleft(6)print q>>deque([6, 0, 1, 2, 3, 4, 5])


0 0
原创粉丝点击