python之Collections容器資料型別

2021-06-25 11:47:37 字數 1206 閱讀 8235

1、ordereddict字典的子類

常規dict並不跟蹤插入順序,迭代處理時會根據鍵在雜湊表中儲存的順序來生成值。

import collections

a={}

>>> a['d']='1'

>>> a['c']='3'

>>> a['b']='4'

>>> a

for k,v in a.items():

print k,v

c 3b 4

d 1

在ordereddict中則相反,它會記住元素的插入順序,並在建立迭代器時候使用中這個順序。

a=collections.ordereddict()

>>> a['d']='1'

>>> a['c']='3'

>>> a['b']='4'

>>> a

ordereddict([('d', '1'), ('c', '3'), ('b', '4')])

2、counter 容器

counter 作為乙個容器,可以跟蹤相同的值增加了多少次

用法:

import collections

#列表形式初始化

print collections.counter([『a』,』b』,』c』,』a』,』c』])

#字典形式初始化

print collections.counter()

#賦值型初始化

print.collections.counter(a=2,b=1,c=2)

#最後的結果都是一樣的

counter()

#建立乙個空的counter 然後用update()方法填充

c=collections.counter()

c.update(『abcdaab』)

#或者c.update()

#eg: import collections

c=collections.counter(『abcdaab』)

for letters in 『abcde』:

print 『%s: %d』 %(letter,c[letters])

#結果輸出

a: 3

b: 2

c: 1

d: 1

e: 0

python常用內建模組 collections

1.namedtuple namedtuple是乙個函式,它用來建立乙個自定義的tuple物件,並且規定了tuple元素的個數,並可以用屬性而不是索引來引用tuple的某個元素。這樣一來,我們用namedtuple可以很方便地定義一種資料型別,它具備tuple的不變性,又可以根據屬性來引用,使用十分...

Python容器資料型別 collections

usr bin python coding utf 8 count物件 only 2.7 from collections import counter 統計字母出現的次數 counter hello world counter red blue red green blue blue 小於等於0的...

Python3之內置模組collections

collections是python內建的乙個集合模組,提供了許多有用的集合類。namedtuple 我們知道tuple可以表示不可變集合,例如,乙個點的二維座標可以表示成 p 1,2 但是,看到 1,2 很難看出這個tuple是用來表示乙個座標的。定義乙個class又小題大做了,這時,namedt...