The Itertools module contains a number of functions that ultimately generate one or more iterators, which are described below:
In order to be able to use the functions in Itertools, you need to import the module:
>>>from Itertools Import *
Count (start=0,step=1):
The source code is:
def count (start=0,step=1): N=start while True:yield n n+=step
As you can see from the source code, the Count function produces a generator that can return a number by default, starting at 0 and increasing by 1 each time. For example:
>>>a=count (2,3) >>>a.next () 2>>>a.next () 5>>>a.next (8)
Of course, start and step can also be decimals. If the sys.maxint is exceeded, the counter overflows, and the-sys.maxint-1 begins to calculate.
Cycle (iterable):
The source code is:
def cycle (iterable): saved=[] for element in Iterable:yield element Saved.append (element) while Tr ue:for element in Saved:yield element
As you can see from the source code, the cycle function creates a list and then stores the elements in the iterable, and finally returns the elements in the list indefinitely. Therefore, the function of the cycle function is to create a generator that returns the elements in an infinite number of parameters, for example:
>>>a=cycle ([1,2,3,4]) >>>a.next () 1>>>a.next () 2>>>a.next () 3>>> A.next () 4>>>a.next () 1
Repeat (Object[,times]):
The source code is as follows:
def repeat (object,times=none): If Times is none:while True:yield object else:for i in XR Ange (Times): Yield object
When the Times is not specified, repeat infinitely repeats, returning the original object. When the Times is specified, the object is returned in a repeated time. For example:
>>>a=repeat (' abc ', 2) >>>a.next () ' ABC ' >>>a.next () ' ABC ' >>>a.next () Stopiteration exception
Description of the Itertools module in python---01