无限迭代器
itertools.count(start, step)
参数:start,生成start开始的连续整数
step为步长,默认为0
def count(start: _N = ...,
step: _N = ...) -> Iterator[_N]
实例1-1
from itertools import *
for i in zip(count(1, 6),['a', 'b','c']):
print(i)
----------------
#(1, 'a')
#(7, 'b')
#(13, 'c')
itertools.cycle(itertool)
对于输入的itertool无限循环操作
实例1-2
from itertools import *
i = 0
for item in cycle(['a', 'b', 'c']):
i += 1
if i == 10:
break
print(i, item)
-----------------
#1 a
#2 b
#3 c
#4 a
#5 b
#6 c
#7 a
#8 b
#9 c
itertools.repeat(object,[time])
创建一个迭代器,重复生成object
实例1-3
from itertools import *
for i in repeat('zaygee', 10):
print(i)
输入序列迭代器
itertools.accumulate(*iterables)
累加器,对列表和迭代器进行累加操作
示例1-4
x = accumulate(range(10))
print(list(x))
-------------------
#[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
itertools.chain(*itertools)
连接多个列表或者迭代器
示例1-5
print(list(chain(['a', 'b', 'c'], ['ee', 'dds', 'efer'])))
------------------------------------------------------
#['a', 'b', 'c', 'ee', 'dds', 'efer']
itertools.compress(data: Iterable[_T],selectors: Iterable)
对data做筛选,按照真值表进行元素筛选
示例1-6
print(list(compress('ABCDEF', [1, 1, 0, 1, 1, 1])))
--------------------------
#['A', 'B', 'D', 'E', 'F']
itertools.groupby(iterable,[key])
对iterable的连续迭代进行分组,key是一个函数,应用于每一项,此函数会返回迭代器的生成元素
示例1-7
x = groupby(range(10), lambda x: x < 5 or x > 8)
for i in x:
print(i)
-------------------
#(True, <itertools._grouper object at 0x000001EC7EE2FC08>)
#(False, <itertools._grouper object at 0x000001EC7EE39CC8>)
#(True, <itertools._grouper object at 0x000001EC7EE39D48>)
x = groupby(range(10), lambda x: x < 5 or x > 8)
for i, j in x:
print(i, list(j))
-------------
#True [0, 1, 2, 3, 4]
#False [5, 6, 7, 8]
#True [9]
itertools.chain.fromiterable(_iterable)
从单独的迭代器得到链式的输入,类似chain()
示例1-8
print(list(chain.from_iterable(['abdddsfs', 'bfsdfsg'])))
------------------------
#['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
from itertools import *
def check_item(x):
print("Checking:{}".format(x))
return (int(x)<1)
for i in filterfalse(check_item, ['-1','1','0']):
print("false:{}".format(i))
----------------------
#Checking:-1
#Checking:1
#false:1
#Checking:0