【python技巧059】用itertools处理各种花样的迭代

本节课大纲:
阿岳每期都是满满的干货啊...
(小约定:红色函数代表在itertools库里,绿色代表是内置函数,蓝色代表在functiontools里)
- 根据一坨东西得到一个东西
- sum函数:求和
- reduce函数:减少。e.g. reduce(f, [a, b, c, d]) <==> f(f(f(a, b), c), d),此处f应为Callable[[Any, Any], Any],即两个输入一个输出
- operator模块:各种运算符
- 去重
- set转集合。e.g. set([1, 2, 3, 1, 4]) == {1, 2, 3, 4}
- groupby 相邻去重。在这里太难写了,看视频吧
- 一坨东西变换得到另一坨东西(映射)
- map函数。e.g. list(map(lambda x: x**2, [1, 2, 5, 9])) == [1, 4, 25, 81]。注意:map函数生成一个map对象,不是列表
- accumulate求前缀和
- 筛选
- filter 传入回调函数。e.g. list(filter(lambda x: x % 2 == 0, arr))只保留偶数。注意:生成一个filter对象
- filterfalse 传入回调函数(看名字也能看出来和filter的区别和联系)注意:生成一个filterfalse对象
- compress 传入一大堆False和True。e.g. list(compress([1, 2, 3, 4, 5], [True, False, False, True, True])) == [1, 4, 5]。注意:生成一个compress对象
- dropwhile抛掉抛掉直到... 传入回调函数。e.g. list(dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1])) == [6, 4, 1]。注意:生成一个dropwhile对象
- takewhile保留保留直到... 传入回调函数。e.g. list(takewhile(lambda x: x < 5, [1, 4, 6, 4, 1])) == [1, 4]。注意:生成一个takewhile对象
- islice 切片儿,不止对列表元组,对一切可迭代对象
- 一坨东西拆成链、合并
- chain 把一大堆一维数组合并成一个一维数组。注意:生成一个chain对象
- chan.from_iterable 把一个二维数组展开成一个一维数组。注意:生成一个chain对象
- pairwise 两两一组(3.10新特性)。e.g. list(pairwise('abcde')) == ['ab', 'bc', 'cd', 'de']
- starmap 用一个函数结合。e.g. list(starmap(pow, [(2, 5), (3, 2), (10, 3)])) == [32, 9, 1000]。注意:生成一个starmap对象
- zip 看短的来
- zip_longest 看长的来
- 排列组合
- product之前讲过(补充:repeat=3)
- permutations(讲过)
- combinations(讲过)
- combinations_with_replacement(讲过)
- 无穷迭代器
- repeat(x, n) 同一个东西x重复n遍;如果没有n,则永久返回x
- count(start=0, step=1) 从start开始永远数下去,可设定步长。enumerate(arr)等价于zip(count(0), arr)
- cycle(iterable) 一个可迭代对象首尾相接一直迭代下去
以上如有错误,欢迎指出
(不得不说用PVZ讲解有一种奇特的效果 )