标签:
举个栗子:
# -*- coding: utf-8 -*-
"""
比如我们用户拥有一个这样的数据结构,每一个对象是拥有三个元素的tuple。
使用namedtuple方法就可以方便的通过tuple来生成可读性更高也更好用的数据结构。
"""
from collections import namedtuple
websites = [
(‘Sohu‘, ‘http://www.google.com/‘, u‘张朝阳‘),
(‘Sina‘, ‘http://www.sina.com.cn/‘, u‘王志东‘),
(‘163‘, ‘http://www.163.com/‘, u‘丁磊‘)
]
Website = namedtuple(‘Website‘, [‘name‘, ‘url‘, ‘founder‘])
for website in websites:
website = Website._make(website)
print website
print website[0], website.url
Website(name=‘Sohu‘, url=‘http://www.google.com/‘, founder=u‘\u5f20\u671d\u9633‘)
Sohu http://www.google.com/
Website(name=‘Sina‘, url=‘http://www.sina.com.cn/‘, founder=u‘\u738b\u5fd7\u4e1c‘)
Sina http://www.sina.com.cn/
Website(name=‘163‘, url=‘http://www.163.com/‘, founder=u‘\u4e01\u78ca‘)
163 http://www.163.com/
l.insert(0, v)
l.pop(0)
但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。
作为一个双端队列,deque还提供了一些其他的好用方法,比如 rotate 等。
# -*- coding: utf-8 -*-
"""
下面这个是一个有趣的例子,主要使用了deque的rotate方法来实现了一个无限循环
的加载动画
"""
import sys
import time
from collections import deque
fancy_loading = deque(‘>--------------------‘)
while True:
print ‘\r%s‘ % ‘‘.join(fancy_loading),
fancy_loading.rotate(1)
sys.stdout.flush()
time.sleep(0.08)
# Result:
# -*- coding: utf-8 -*-
"""
下面这个例子就是使用Counter模块统计一段句子里面所有字符出现次数
"""
from collections import Counter
s = ‘‘‘A Counter is a dict subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys
and their counts are stored as dictionary values. Counts are allowed to be
any integer value including zero or negative counts. The Counter class is
similar to bags or multisets in other languages.‘‘‘.lower()
c = Counter(s)
# 获取出现频率最高的5个字符
print c.most_common(5)
# Result:
# -*- coding: utf-8 -*-
from collections import OrderedDict
items = (
(‘A‘, 1),
(‘B‘, 2),
(‘C‘, 3)
)
regular_dict = dict(items)
ordered_dict = OrderedDict(items)
print ‘Regular Dict:‘
for k, v in regular_dict.items():
print k, v
print ‘Ordered Dict:‘
for k, v in ordered_dict.items():
print k, v
# Result: # -*- coding: utf-8 -*-
from collections import defaultdict
members = [
# Age, name
[‘male‘, ‘John‘],
[‘male‘, ‘Jack‘],
[‘female‘, ‘Lily‘],
[‘male‘, ‘Pony‘],
[‘female‘, ‘Lucy‘],
]
result = defaultdict(list)
for sex, name in members:
result[sex].append(name)
print result
# Result:解释:
Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists.
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():
d = {}
for k, v in s:
d.setdefault(k, []).append(v)
d.items()
https://docs.python.org/2/library/collections.html#module-collections
http://python.jobbole.com/65218/ Python中的高级数据结构
标签:
原文地址:http://www.cnblogs.com/fclbky/p/5600222.html