python模組之collections模組

xuxianshen發表於2019-01-04

計數器 Counter

  • 計數元素迭代器 elements()
  • 計數物件拷貝 copy()
  • 計數物件清空 clear()
from collections import Counter
#import collections
d = Counter("abdadakdabfdj")  #對值計數,返回一個物件
print(d, type(d))               #Counter({`a`: 4, `d`: 4, `b`: 2, `k`: 1, `f`: 1, `j`: 1}) <class `collections.Counter`>
print(list(d), type(d))         #[`a`, `b`, `d`, `k`, `f`, `j`] <class `collections.Counter`>
print(dict(d), type(d))         #{`a`: 4, `b`: 2, `d`: 4, `k`: 1, `f`: 1, `j`: 1} <class `collections.Counter`>
print(d.elements())   #elements()方法返回一個迭代器,內容為進行計數的元素
for i in d.elements():
    print(i)       # a a a a d d d d b b k f j
d1 = d.copy()
print(d1,type(d1))       #Counter({`a`: 4, `d`: 4, `b`: 2, `k`: 1, `f`: 1, `j`: 1}) <class `collections.Counter`>
d2 = d.subtract("aaa")
print(d2,type(d2))
d3 = d.update(`aaa`)
print(d3,type(d3))
d4 = d.pop("j")
print(d4,d)   #  1    Counter({`a`: 4, `d`: 4, `b`: 2, `k`: 1, `f`: 1})
d.clear() # clear()方法清空計數的元素
print(d)    #  Counter()

有序字典 OrderedDict  (對字典的補充,可以記住字典元素新增的順序)

from collections import OrderedDict

order_dict = OrderedDict()
print(order_dict,type(order_dict))
order_dict["c"] = 94
order_dict["b"] = 92
order_dict["d"] = 95
order_dict["a"] = 90
print(order_dict,type(order_dict))      #返回有序字典物件,OrderedDict([(`c`, 94), (`b`, 92), (`d`, 95), (`a`, 90)]) <class `collections.OrderedDict`>
print(dict(order_dict),type(order_dict))#{`c`: 94, `b`: 92, `d`: 95, `a`: 90} <class `collections.OrderedDict`>
print(list(order_dict),type(order_dict))#[`c`, `b`, `d`, `a`] <class `collections.OrderedDict`>
print(order_dict.popitem())  #提取出字典的最後一個鍵值對  (`a`, 90)
print(order_dict)           #OrderedDict([(`c`, 94), (`b`, 92), (`d`, 95)])
print(order_dict.pop("b"))  #提取出字典指定鍵對應的值
print(order_dict)           #OrderedDict([(`c`, 94), (`d`, 95)])
order_dict.move_to_end("c") #將指定的鍵值對移動到最後
print(order_dict)           #OrderedDict([(`d`, 95), (`c`, 94)])

 預設字典 defaultdict,(指定字典值的型別)

from collections import defaultdict

default_dict = defaultdict(list)   # 指定字典的值型別為列表
print(default_dict,type(default_dict))   #defaultdict(<class `list`>, {}) <class `collections.defaultdict`>

for i in range(10):
    default_dict["a"].append(i)

print(default_dict)   #defaultdict(<class `list`>, {`a`: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]})

 

 可命名元組 namedtuple (給元組對應的值起個對應的名字,相當於字典)

from collections import namedtuple

tuple1 = namedtuple("tuple_name",["name","age","school","adress"])
print(tuple1)
tuple1 = tuple1("xu",20,"jinggangshan","jiangxi")
print(tuple1.name)

 

相關文章