python set集合 heapq堆模块 双端队列deque
=========================================set集合=======================
>>> set(range(10))
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a = set([1,2,3])
>>> b = set([2,3,4])
>>> a.union(b)
set([1, 2, 3, 4])
>>> a|b
set([1, 2, 3, 4])
>>> a&b
set([2, 3])
集合的遍历
>>> for x in a:
print x
集合的增删
>>> 1 in a
True
>>> 1 not in a
False
>>> a.add(4)
>>> a
set([1, 2, 3, 4])
>>> a.remove(4)
>>> a
set([1, 2, 3])
s.update(t)
s |= t
返回增加了 set “t”中元素后的 set “s”
s.intersection_update(t)
s &= t
返回只保留含有 set “t”中元素的 set “s”
s.difference_update(t)
s -= t
返回删除了 set “t”中含有的元素后的 set “s”
s.symmetric_difference_update(t)
s ^= t
返回含有 set “t”或者 set “s”中有而不是两者都有的元素的 set “s”
s.add(x)
向 set “s”中增加元素 x
s.remove(x)
从 set “s”中删除元素 x, 如果不存在则引发 KeyError
s.discard(x)
如果在 set “s”中存在元素 x, 则删除
s.pop()
删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyError
s.clear()
删除 set “s”中的所有元素
=========================heapq堆模块==================================
>>> from random import shuffle
>>> data = range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> from heapq import *
>>> shuffle(data)
>>> data
[5, 0, 3, 8, 2, 6, 7, 9, 4, 1]
>>> heap=[]
>>> for n in data:
heappush(heap,n)
>>> heap
[0, 1, 3, 4, 2, 6, 7, 9, 8, 5]
>>> heappush(heap,0.5)
>>> heap
[0, 0.5, 3, 4, 1, 6, 7, 9, 8, 5, 2]
>>> heappop(heap)
0
>>> heap
[0.5, 1, 3, 4, 2, 6, 7, 9, 8, 5]
=======================================deque=============================
>>> from collections import deque
>>> q=deque(range(5))
>>> q
deque([0, 1, 2, 3, 4])
>>> q.append(5)
>>> q
deque([0, 1, 2, 3, 4, 5])
>>> q.pop()
5