您的位置:首页 > 编程语言 > Python开发

python之Collections容器数据类型

2014-09-06 14:20 393 查看
1、OrderedDict字典的子类

常规dict并不跟踪插入顺序,迭代处理时会根据键在散列表中存储的顺序来生成值。

<span style="font-size:18px;">import collections
a={}
>>> a['d']='1'
>>> a['c']='3'
>>> a['b']='4'
>>> a
{'c': '3', 'b': '4', 'd': '1'}
for k,v in a.items():
print k,v

c 3
b 4
d 1
</span>


在OrderedDict中则相反,它会记住元素的插入顺序,并在创建迭代器时候使用中这个顺序。

<span style="font-size:18px;">a=collections.OrderedDict()
>>> a['d']='1'
>>> a['c']='3'
>>> a['b']='4'
>>> a
OrderedDict([('d', '1'), ('c', '3'), ('b', '4')])
</span>

2、Counter 容器
Counter 作为一个容器,可以跟踪相同的值增加了多少次

用法:<span style="font-size:18px;">import collections
#列表形式初始化
print collections.Counter([‘a’,’b’,’c’,’a’,’c’])
#字典形式初始化
print collections.Counter({‘a’:2,’b’:1,’c’:2})
#赋值型初始化
Print.collections.Counter(a=2,b=1,c=2)

#最后的结果都是一样的
Counter({‘b’:2,’a’:1,’c’:2})

#创建一个空的Counter 然后用update()方法填充
c=collections.Counter()
c.update(‘abcdaab’)

#或者
c.update({‘a’:1,’d’:5})

#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</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息