python之Collections容器数据类型
2014-09-06 14:20
393 查看
1、OrderedDict字典的子类
常规dict并不跟踪插入顺序,迭代处理时会根据键在散列表中存储的顺序来生成值。
在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>
常规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>
相关文章推荐
- [Python标准库]collections——容器数据类型[二]
- Python容器数据类型——collections
- [Python标准库]collections——容器数据类型[一]
- Python容器的数据类型 (python2)
- Python高级数据类型模块collections
- 【Python】 更多数据类型collections&简易数据文件shelve
- collections 容器数据类型
- collections——高性能容器数据类型
- python基础数据类型及内置容器详解
- Python 入门(2)--数据类型和变量
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义sqlite3数据表字段数据类型
- 004--从C#到Python —— 1 变量和数据类型
- Python笔记——基本语法:标识符、数据类型、变量、运算符及表达式/编码风格
- python中如何判断一个变量的数据类型
- python学习笔记(一) 基本数据类型及运算
- python内置数据类型
- 讨论python的数据类型的区别
- Python语言学习(2)-Python基本数据类型
- python笔记(二) - 数据类型
- python语法31[基本数据类型和流程控制]