第二十五章:collections与itertools
本章目标
完成本章学习后,你将能够:
- 使用collections的高级数据结构
- 掌握itertools的迭代工具
- 编写高效的迭代代码
collections模块
from collections import Counter, defaultdict, OrderedDict, deque, namedtuple # Counter words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'] count = Counter(words) print(count.most_common(2)) # [('apple', 3), ('banana', 2)] # defaultdict groups = defaultdict(list) for word in words: groups[len(word)].append(word) # namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # OrderedDict(Python 3.7+ dict也是有序的) od = OrderedDict() od['a'] = 1 od['b'] = 2
itertools模块
import itertools # 无限迭代器 count = itertools.count(10, 2) # 10, 12, 14, ... cycle = itertools.cycle('ABC') # A, B, C, A, B, C, ... repeat = itertools.repeat(10, 3) # 10, 10, 10 # 组合 print(list(itertools.combinations('ABC', 2))) # [('A','B'), ('A','C'), ('B','C')] print(list(itertools.permutations('ABC', 2))) # 所有排列 print(list(itertools.product('AB', '12'))) # 笛卡尔积 # 过滤和分组 data = [1, 2, 3, 4, 5, 6] print(list(itertools.filterfalse(lambda x: x % 2, data))) # 分组 for key, group in itertools.groupby('AAAABBBCCD'): print(key, list(group)) # 拉链 print(list(itertools.zip_longest([1,2], ['a','b','c'], fillvalue='-')))
本章练习
1. 使用Counter统计文本 2. 使用itertools生成排列组合 3. 实现滑动窗口 4. 使用namedtuple重构代码
下一章:第二十六章:正则表达式