1.set(集合)
set和dict類似,也是一組key的集合,但不存儲value。由于key不能重複,是以,在set中,沒有重複的key。
集合和我們數學中集合的概念是一樣的,也有交集、并集、差集、對稱差集等概念。
1.1定義集合需要提供一個清單作為參數,也可以不傳參數建立一個空集合
>>> s = set([1, 2, 2, 3])
>>> s
{1, 2, 3} # 可以看到在建立集合對象對過程中已經為我們把重複的元素剔除掉了
>>> s = set()
set()
1.2set常用方法
#python3.x
dir(set)
#['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

s = set([1, 2, 3])
s.add(4)
print(s)
"""
添加一個新的元素,如果該元素已經存在,将不會有任何操作
Add an element to a set.
This has no effect if the element is already present.
"""
#輸出{1, 2, 3, 4}
add 添加元素

s = set([1, 2, 3])
s.clear()
print(s)
"""
删除所有元素
return:None
Remove all elements from this set.
"""
#輸出set()
clear 清空集合

A = set([1, 2, 3])
B = set([2, 3, 4])
print(A.difference(B))
"""
求目前差集和另一個集合的差集
return:差集
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
"""
#輸出{1}
difference 差集

A = set([1, 2, 3])
B = set([2, 3, 4])
A.difference_update(B)
print(A)
"""
從目前集合中删除所有另一個集合中存在的元素
其實就相當于将difference傳回的值又付給了目前集合
可以了解為A = A - B,或者A -= B
Remove all elements of another set from this set.
"""
#輸出集合A結果為{1}
difference_update 差集

A = set([1, 2, 3])
A.discard(2)
print(A) #輸出{1, 3}
A.discard(4)
print(A) #輸出{1, 3}
"""
如果一個集合中存在這個元素則删除,否則什麼都不做
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
"""
discard 從集合中删除元素

A = set([1, 2, 3])
B = set([2, 3, 4])
print(B.intersection(A)) #輸出{2, 3}
"""
傳回兩個集合的交集到一個新的集合中
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
"""
intersection 交集

A = set([1, 2, 3])
B = set([2, 3, 4])
A.intersection_update(B)
print(A) #輸出{2, 3}
"""
求一個集合與另一個集合的交集,并把結果傳回目前集合
Update a set with the intersection of itself and another.
"""
intersection_update 交集

A = set([1, 2, 3])
B = set([2, 3, 4])
print(A.isdisjoint(B)) #輸出False
A = set([1, 2, 3])
B = set([4, 5, 6])
print(A.isdisjoint(B)) #輸出True
"""
判斷兩個集合是否存在交集,有傳回False,沒有傳回True
Return True if two sets have a null intersection.
"""
isdisjoint 判斷是否有交集(注意:這裡是沒有交集傳回True,有交集傳回False,有點别扭,但不要搞反了)

A = set([1, 2, 3])
B = set([1, 2, 3, 4])
print(A.issuperset(B)) #輸出False
print(B.issuperset(A)) #輸出True
"""
判斷目前集合是否是另一個集合父集合(另一個集合的所有元素都在目前集合中)
Report whether this set contains another set.
"""
issuperset 判斷目前集合是否是另一個集合的父集合(包括等于)

s = set([1, 2, 3])
a = s.pop()
print(a) #輸出1
print(s) #輸出{2, 3}
"""
随機删除一個元素,并傳回那個元素,如果集合為空,将會抛出KeyError異常
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pop 随機删除元素,并傳回删除的元素

s = set([1, 2, 3])
s.remove(2)
print(s) #輸出{1, 3}
"""
從集合中删除一個元素,如果要删除的元素不在集合,将會抛出KeyError異常
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
"""
remove 删除一個元素

A = set([1, 2, 3])
B = set([2, 3, 4, 5])
print(A.symmetric_difference(B)) #輸出{1, 4, 5}
print(B.symmetric_difference(A)) #輸出{1, 4, 5}
"""
傳回兩個集合的對稱差集到一個新的集合
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
symmetric_difference 傳回兩個集合的對稱差集

A = set([1, 2, 3])
B = set([2, 3, 4, 5])
A.symmetric_difference_update(B)
print(A) #輸出{1, 4, 5}
"""
更新目前集合為與另外一個集合的對稱差集
Update a set with the symmetric difference of itself and another.
"""
symmetric_difference_update 目前集合更新為與另一個集合的對稱差集

A = set([1, 2, 3])
B = set([2, 3, 4, 5])
print(A.union(B)) #輸出{1, 2, 3, 4, 5}
print(B.union(A)) #輸出{1, 2, 3, 4, 5}
"""
傳回與另一個集合的并集為一個新的集合
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
"""
union 傳回與另一個集合的并集為一個新的集合

A = set([1, 2, 3])
B = set([2, 3, 4, 5])
A.update(B)
print(A) #輸出{1, 2, 3, 4, 5}
"""
更新目前集合為與另一個集合的并集
Update a set with the union of itself and others.
"""
update 更新目前集合為與另一個集合的并集
2.collections
collections是對Python現有的資料類型的補充,在使用collections中的對象要先導入import collections子產品
2.1Counter--計數器
計數器是對字典的補充,繼承自字典,除了具有字典的所有方法,還有很多擴充功能。
定義Counter對象
Counter接受一個序列對象,如list、tuple、str等,傳回以字典形式(按照出現次數倒序)
import collections
c = collections.Counter("asfsdfsdfgsdgf")
print(c)
c1 = collections.Counter(['tom', 'jack', 'tony', 'jack'])
print(c1)
'''
輸出結果
Counter({'s': 4, 'f': 4, 'd': 3, 'g': 2, 'a': 1})
Counter({'jack': 2, 'tom': 1, 'tony': 1})
'''
2.2Counter常用方法
#python3.x
dir(collections.Counter())
#['__add__', '__and__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__le__', '__len__', '__lt__', '__missing__', '__module__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__weakref__', '_keep_positive', 'clear', 'copy', 'elements', 'fromkeys', 'get', 'items', 'keys', 'most_common', 'pop', 'popitem', 'setdefault', 'subtract', 'update', 'values']

c = collections.Counter("dsadfasfasfasf")
print(c.most_common(3))
print(c.most_common(2))
'''
輸出
[('s', 4), ('a', 4), ('f', 4)]
[('s', 4), ('a', 4)]
'''
most_common——傳回前幾個的元素和對應出現的次數(按照出現次數的倒序排列)

c = collections.Counter("safasfsadasdas")
print(c.elements())
print(list(c.elements()))
'''
輸出
<itertools.chain object at 0x0000000005040C88>
['s', 's', 's', 's', 's', 'a', 'a', 'a', 'a', 'a', 'f', 'f', 'd', 'd']
注意:傳回的是一個疊代器對象,可以通過内置方法将其轉化為清單對象,也可以通過for in進行周遊
'''
elements——傳回所有元素,疊代器對象

c = collections.Counter(['tom', 'jack', 'tony', 'jack'])
c.update('peter')
print(c) # 注意參數是一個序列對象,如果傳的是一個字元串,字元串的每一個字元都會被當成一個元素
c = collections.Counter(['tom', 'jack', 'tony', 'jack'])
c.update(['tom'])
print(c)
'''
輸出
Counter({'jack': 2, 'e': 2, 'tom': 1, 'tony': 1, 'p': 1, 't': 1, 'r': 1})
Counter({'tom': 2, 'jack': 2, 'tony': 1})
'''
update——添加一個新的成員,如果存在計數器的值進行累加,如果不存在将建立一個成員

c = collections.Counter(['tom', 'jack', 'tony', 'jack'])
c.subtract(['tom'])
print(c)
c.subtract(['tom'])
print(c)
'''
輸出
Counter({'jack': 2, 'tony': 1, 'tom': 0})
Counter({'jack': 2, 'tony': 1, 'tom': -1})
注意:
注意:如果成員已經不存在了或者說為0了,計數器會繼續遞減,也就是說計數器有0和負數的概念的,但是使用elements顯示的時候卻沒有該成員,如果計時器是0或者負數能說明這個成員出現過而已,另外如果為負數的時候,添加成員,成員不會真的添加到elements顯示的成員中,直到計數器大于0為止
'''
subtract——減去一個成員,計數器減1
3.OrderedDict 有序字典
我們都知道字典是無序的,OrderedDict 是對字典的擴充,使其有序,并根據添加順序進行排序
c = collections.OrderedDict()
我們也可以通過一個現有的字典進行初始化有序字典
old_dict = {'k1':'1', 'k2':'2', 'k3':'3'}
new_dict = collections.OrderedDict(old_dict)
print(new_dict)
#輸出OrderedDict([('k1', '1'), ('k2', '2'), ('k3', '3')])
有序字典常用方法
old_dict = {'k1':'1', 'k2':'2', 'k3':'3'}
new_dict = collections.OrderedDict(old_dict)
dir(new_dict)
#['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'move_to_end', 'pop', 'popitem', 'setdefault', 'update', 'values']

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
dic.clear()
print(dic)
'''
輸出OrderedDict()
'''
clear——清空字典

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
print(dic.keys())
'''
輸出:odict_keys(['a', 'b', 'c'])
'''
keys——傳回所有key組成的疊代對象

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
print(dic.values())
#輸出odict_values([1, 2, 3])
values——傳回所有value組成的疊代對象

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
print(dic.items())
#輸出odict_items([('a', 1), ('b', 2), ('c', 3)])
items——傳回key和value組成的疊代對象

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
print(dic.pop('b')) #輸出2
print(dic) #輸出OrderedDict([('a', 1), ('c', 3)])
print(dic.pop('d', 10)) #輸出10
'''
删除指定key的元素,并傳回key所對應的值
k:要删除的元素的key
d:如果key不存在傳回的預設值
'''
pop——删除指定key的元素

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
print(dic.popitem()) #輸出('c', 3)
"""
删除末尾的元素,并傳回删除的元素的key和value
"""
popitem——删除末尾的元素

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
"""
設定某個鍵的預設值,使用get方法如果該鍵不存在傳回的值
"""
pass
setdefault——設定預設值

def move_to_end(self, *args, **kwargs): # real signature unknown
"""
移動一個元素到字典的末尾,如果該元素不存在這回抛出KeyError異常
同原生字典,不同的是有序和無序
"""
update——将另一個字典更新到目前字典

dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
dic.move_to_end('b')
print(dic) #輸出OrderedDict([('a', 1), ('c', 3), ('b', 2)])
"""
移動一個元素到字典的末尾,如果該元素不存在這回抛出KeyError異常
"""
move_to_end——将一個存在的元素移動到字典的末尾

dic = collections.defaultdict(list) #定義的時候需要指定預設的資料類型,這裡指定的是清單類型
dic['k1'].append('a') #盡管目前key還沒有值,但是它預設已經是清單類型,是以直接可以用清單的append方法
print(dic) #輸出defaultdict(<class 'list'>, {'k1': ['a']})
"""
defaultdict是對字典的擴充,它預設個給字典的值設定了一種預設的資料類型,其他的均與原生字典一樣
"""
defaultdict——預設字典
4.namedtuple可命名元組
可命名元組是元組的擴充,包含所有元組的方法的同時可以給每個元組的元素命名,通路時候也不需要再通過索引進行通路,直接通過元素名即可通路
MytupleClass = collections.namedtuple('MytupleClass',['x', 'y', 'z'])
mytuple = MytupleClass(11, 22, 33)
print(mytuple.x) #11
print(mytuple.y) #22
print(mytuple.z) #33
5.deque雙向隊列
deque是一個線程安全的雙向隊列,類似清單,不同的是,deque是線程安全,并且是雙向的也就是兩邊都可以進出
5.1定義雙向隊列
d = collections.deque()
5.2常用方法
d = collections.deque()
dir(d)
#['__add__', '__bool__', '__class__', '__contains__', '__copy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'appendleft', 'clear', 'copy', 'count', 'extend', 'extendleft', 'index', 'insert', 'maxlen', 'pop', 'popleft', 'remove', 'reverse', 'rotate']

d = collections.deque([1, 2, 3])
d.append(4)
print(d) #輸出deque([1, 2, 3, 4])
"""
從右邊追加一個元素到隊列的末尾
"""
append——從右邊追加一個元素到隊列的末尾

d = collections.deque([1, 2, 3])
d.appendleft(4)
print(d) #輸出deque([4, 1, 2, 3])
"""
從左邊追加一個元素到隊列的末尾
"""
appendleft——從左邊追加一個元素到隊列的末尾

d = collections.deque([1, 2, 3])
d.clear()
print(d) #deque([])
"""
清空隊列
"""
clear——清空隊列

d = collections.deque([1, 2, 3, 1])
print(d.count(1)) #輸出2
count——傳回某個成員重複出現的次數

d = collections.deque([1, 2, 3])
d.extend([4, 5])
print(d) #輸出deque([1, 2, 3, 4, 5])
extend——從隊列右邊擴充一個可疊代的對象

d = collections.deque([1, 2, 3])
d.extendleft([4, 6])
print(d) #輸出deque([6, 4, 1, 2, 3])
extendleft——從隊列左側擴充一個可疊代的對象

def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
查找元素是否存在,如果不存在将會抛出ValueError異常,如果存在傳回第一找到的索引位置
value:要查找的元素
start:查找的開始是以你能
stop:查找的結束索引
"""
return 0
#使用方法同清單,需要說明雖然是雙向隊列,但是索引還是從左到右編碼的
index——查找并傳回索引

d = collections.deque([1, 2, 3])
d.insert(0, 4)
print(d) #deque([4, 1, 2, 3])
insert——插入索引

d = collections.deque([1, 2, 3])
print(d.pop()) #輸出3
print(d) #輸出deque([1, 2])
pop——從隊列右側末尾删除一個元素,并傳回該元素

d = collections.deque([1, 2, 3])
print(d.popleft()) #輸出1
print(d) #輸出deque([2, 3])
popleft——從隊列左側删除一個元素,并傳回該元素

d = collections.deque([1, 2, 3, 2])
d.remove(2)
print(d) #輸出deque([1, 3, 2])
remove——删除一個元素

d = collections.deque([1, 2, 3])
d.reverse()
print(d) #輸出deque([3, 2, 1])
reverse——翻轉隊列

d = collections.deque([1, 2, 3, 4, 5])
d.rotate(2)
print(d)
"""
隊列旋轉,預設移動1位
輸出deque([4, 5, 1, 2, 3])
雙向隊列的旋轉可以了解為,雙向隊列的首位是相連的環,旋轉就是元素移動了多少個位置,如下圖所示,或者說從左邊取出元素追加到右邊,追加了多少次
"""
rotate——旋轉隊列