欢迎光临散文网 会员登陆 & 注册

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

2022-12-29 21:44 作者:小倪同学0v0  | 我要投稿

本节课大纲:

阿岳每期都是满满的干货啊...

(小约定:红色函数代表在itertools库里,绿色代表是内置函数,蓝色代表在functiontools里)

  1. 根据一坨东西得到一个东西
  2. sum函数:求和
  3. reduce函数:减少。e.g. reduce(f, [a, b, c, d]) <==> f(f(f(a, b), c), d),此处f应为Callable[[Any, Any], Any],即两个输入一个输出
  4. operator模块:各种运算符
  5. 去重
  6. set转集合。e.g. set([1, 2, 3, 1, 4]) == {1, 2, 3, 4}
  7. groupby 相邻去重。在这里太难写了,看视频吧
  8. 一坨东西变换得到另一坨东西(映射)
  9. map函数。e.g. list(map(lambda x: x**2, [1, 2, 5, 9])) == [1, 4, 25, 81]。注意:map函数生成一个map对象,不是列表
  10. accumulate求前缀和
  11. 筛选
  12. filter 传入回调函数。e.g. list(filter(lambda x: x % 2 == 0, arr))只保留偶数。注意:生成一个filter对象
  13. filterfalse 传入回调函数(看名字也能看出来和filter的区别和联系)注意:生成一个filterfalse对象
  14. compress 传入一大堆False和True。e.g. list(compress([1, 2, 3, 4, 5], [True, False, False, True, True])) == [1, 4, 5]。注意:生成一个compress对象
  15. dropwhile抛掉抛掉直到... 传入回调函数。e.g. list(dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1])) == [6, 4, 1]。注意:生成一个dropwhile对象
  16. takewhile保留保留直到... 传入回调函数。e.g. list(takewhile(lambda x: x < 5, [1, 4, 6, 4, 1])) == [1, 4]。注意:生成一个takewhile对象
  17. islice 切片儿,不止对列表元组,对一切可迭代对象
  18. 一坨东西拆成链、合并
  19. chain 把一大堆一维数组合并成一个一维数组。注意:生成一个chain对象
  20. chan.from_iterable 把一个二维数组展开成一个一维数组。注意:生成一个chain对象
  21. pairwise 两两一组(3.10新特性)。e.g. list(pairwise('abcde')) == ['ab', 'bc', 'cd', 'de']
  22. starmap 用一个函数结合。e.g. list(starmap(pow, [(2, 5), (3, 2), (10, 3)])) == [32, 9, 1000]。注意:生成一个starmap对象
  23. zip 看短的来
  24. zip_longest 看长的来
  25. 排列组合
  26. product之前讲过(补充:repeat=3)
  27. permutations(讲过)
  28. combinations(讲过)
  29. combinations_with_replacement(讲过)
  30. 无穷迭代器
  31. repeat(x, n) 同一个东西x重复n遍;如果没有n,则永久返回x
  32. count(start=0, step=1)start开始永远数下去,可设定步长。enumerate(arr)等价于zip(count(0), arr)
  33. cycle(iterable) 一个可迭代对象首尾相接一直迭代下去

以上如有错误,欢迎指出

(不得不说用PVZ讲解有一种奇特的效果 )

【python技巧059】用itertools处理各种花样的迭代的评论 (共 条)

分享到微博请遵守国家法律