无限迭代器

itertools.count(start, step)

参数:start,生成start开始的连续整数
step为步长,默认为0

  1. def count(start: _N = ...,
  2. step: _N = ...) -> Iterator[_N]

实例1-1

  1. from itertools import *
  2. for i in zip(count(1, 6),['a', 'b','c']):
  3. print(i)
  4. ----------------
  5. #(1, 'a')
  6. #(7, 'b')
  7. #(13, 'c')

itertools.cycle(itertool)

对于输入的itertool无限循环操作
实例1-2

  1. from itertools import *
  2. i = 0
  3. for item in cycle(['a', 'b', 'c']):
  4. i += 1
  5. if i == 10:
  6. break
  7. print(i, item)
  8. -----------------
  9. #1 a
  10. #2 b
  11. #3 c
  12. #4 a
  13. #5 b
  14. #6 c
  15. #7 a
  16. #8 b
  17. #9 c

itertools.repeat(object,[time])

创建一个迭代器,重复生成object
实例1-3

  1. from itertools import *
  2. for i in repeat('zaygee', 10):
  3. print(i)

输入序列迭代器

itertools.accumulate(*iterables)

累加器,对列表和迭代器进行累加操作
示例1-4

  1. x = accumulate(range(10))
  2. print(list(x))
  3. -------------------
  4. #[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

itertools.chain(*itertools)

连接多个列表或者迭代器
示例1-5

  1. print(list(chain(['a', 'b', 'c'], ['ee', 'dds', 'efer'])))
  2. ------------------------------------------------------
  3. #['a', 'b', 'c', 'ee', 'dds', 'efer']

itertools.compress(data: Iterable[_T],selectors: Iterable)

对data做筛选,按照真值表进行元素筛选
示例1-6

  1. print(list(compress('ABCDEF', [1, 1, 0, 1, 1, 1])))
  2. --------------------------
  3. #['A', 'B', 'D', 'E', 'F']

itertools.groupby(iterable,[key])

对iterable的连续迭代进行分组,key是一个函数,应用于每一项,此函数会返回迭代器的生成元素
示例1-7

  1. x = groupby(range(10), lambda x: x < 5 or x > 8)
  2. for i in x:
  3. print(i)
  4. -------------------
  5. #(True, <itertools._grouper object at 0x000001EC7EE2FC08>)
  6. #(False, <itertools._grouper object at 0x000001EC7EE39CC8>)
  7. #(True, <itertools._grouper object at 0x000001EC7EE39D48>)
  8. x = groupby(range(10), lambda x: x < 5 or x > 8)
  9. for i, j in x:
  10. print(i, list(j))
  11. -------------
  12. #True [0, 1, 2, 3, 4]
  13. #False [5, 6, 7, 8]
  14. #True [9]

itertools.chain.fromiterable(_iterable)

从单独的迭代器得到链式的输入,类似chain()
示例1-8

  1. print(list(chain.from_iterable(['abdddsfs', 'bfsdfsg'])))
  2. ------------------------
  3. #['a', 'b', 'd', 'd', 'd', 's', 'f', 's', 'b', 'f', 's', 'd', 'f', 's', 'g']

itertools.filterfalse(predicate: Any, iterable: Iterable[_T])

创建一个迭代器,只返回predicate为false的元素
示例1-9

  1. from itertools import *
  2. def check_item(x):
  3. print("Checking:{}".format(x))
  4. return (int(x)<1)
  5. for i in filterfalse(check_item, ['-1','1','0']):
  6. print("false:{}".format(i))
  7. ----------------------
  8. #Checking:-1
  9. #Checking:1
  10. #false:1
  11. #Checking:0