This article illustrates the use of Itertools modules in Python and share them for your reference. The specific analysis is as follows:
Generally speaking, the Itertools module contains functions to create a valid iterator that can be iterated over in various ways, and the iterator returned by all functions in this module can be used in conjunction with a For Loop statement and other functions that contain iterators, such as generators and builder expressions.
Chain (Iter1, Iter2, ..., itern):
Gives a set of Iterators (Iter1, Iter2, ..., Itern), which creates a new iterator to link all the iterators, the returned iterators start generating items from Iter1, know that the iter1 is run out, and then generate the items from Iter2, This process lasts until all the items in the Itern are exhausted.
From Itertools import chain
test = Chain (' AB ', ' CDE ', ' F ') for
el in test:
print el
A
B
C
d
e
F
Chain.from_iterable (iterables):
An alternate chain constructor in which the Iterables is an iterative variable that generates an iteration sequence that results in the same result as the following generator code fragment:
>>> def f (iterables): For
x in iterables: For
y in x:
yield y
>>> test = f (' ABCDEF ')
>>> test.next ()
' A '
>>> from itertools import chain
>>> test = chain.from_ Iterable (' ABCDEF ')
>>> test.next ()
' A '
Combinations (iterable, R):
Creates an iterator that returns all the iterable of the length r in the sequence, and the items in the returned subsequence sorted in the order of the input iterable:
>>> from Itertools import combinations
>>> test = combinations ([1,2,3,4], 2)
>>> For El in test:
print El
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(
2, 4) (3, 4)
Count ([n]):
Creates an iterator that generates consecutive integers starting with n and, if n is omitted, evaluates from 0 (note: This iterator does not support long integers), and if Sys.maxint is exceeded, the counter overflows and continues to compute from-sys.maxint-1.
Cycle (iterable):
Creates an iterator that iterates through the elements in the iterable and internally generates a copy of the elements in the iterable, which is used to return duplicates in the loop.
Dropwhile (predicate, iterable):
Creates an iterator that discards the items in iterable if the function predicate (item) is true, and if predicate returns false, the items in iterable and all subsequent items are generated.
def dropwhile (predicate, iterable):
# dropwhile (Lambda x:x<5, [1,4,6,4,1])--> 6 4 1
iterable = iter (iterab Le) for
x in iterable:
if does predicate (x):
yield x break for x in
iterable:
yield x
GroupBy (iterable [, key]):
Creates an iterator that groups contiguous items that are generated by iterable, and finds duplicates during grouping.
If iterable produces the same item in multiple consecutive iterations, a group is defined, and if you apply a category list to this function, the grouping defines all the unique items in the list, and key (if provided) is a function, applied to each item, if there is a return value for this function, This value will be used for subsequent entries rather than for the item itself, which returns an iterator-generated element (key, group), where key is a grouped key value, and a group is an iterator that generates all the items that make up the group.
IFilter (predicate, iterable):
creates an iterator that generates only items of predicate (item) True in Iterable and, if predicate is None, returns all items in iterable that are evaluated to true.
IFilter (Lambda x:x%2, Range ())--> 1 3 5 7 9
ifilterfalse (predicate, iterable):
creates an iterator that generates only items of predicate (item) False in Iterable, and if predicate is none, returns all items in iterable that are evaluated as false.
Ifilterfalse (Lambda x:x%2, Range ())--> 0 2 4 6 8
IMAP (function, Iter1, Iter2, Iter3, ..., Itern)
creates an iterator that generates the item function (I1, I2, ..., in), where I1,i2...in comes from the iterator iter1,iter2 ... itern, if the function is None, returns (I1, I2, ..., in As long as one of the provided iterators no longer generates a value, the iteration stops.
>>> from itertools import *
>>> d = IMAP (POW, (2,3,10), (5,2,3))
>>> to I in D:print I
9
1000
#
>>> d = IMAP (POW, (2,3,10), (5,2)) >>> for i in
d:print i
32
9
#
>>> d = IMAP (None, (2,3,10), (5,2))
>>> for i in D:print I
(2, 5) c15/> (3, 2)
Islice (iterable, [Start,] stop [, step]):
creates an iterator that generates items in a manner similar to the slice return value: iterable[start:stop:step], skips the first start, iterates over the position specified by the stop, and step specifies the stride to skip the item. Unlike slices, negative values are not used for any start,stop and step, and if you omit start, the iterations start at 0, and if you omit step, the stride takes 1.
def islice (Iterable, *args):
# islice (' ABCDEFG ', 2)--> A B
# islice (' ABCDEFG ', 2, 4)--> C D
# islice (' ABCDEFG ', 2, none)--> C D e F g
# islice (' ABCDEFG ', 0, none, 2)--> A C e G
s = Slice (*args)
it = iter ( Xrange (s.start or 0, s.stop or sys.maxint, s.step or 1))
Nexti = Next (it)
for I, element in enumerate (iterable):
if i = = Nexti:
yield element
Nexti = Next (it)
#If Start is None and then iteration starts at zero. If step is None, then the "step" defaults to one.
#Changed in version 2.5:accept the None values for default start and step.
Izip (Iter1, Iter2, ... itern):
Create an iterator, generate tuples (I1, I2, ... in), where i1,i2 ... in, from iterators iter1,iter2 ... itern, as long as one of the supplied iterators no longer generates a value, the iteration stops, and the value generated by this function is the built-in zip () function is the same.
def izip (*iterables):
# izip (' ABCD ', ' xy ')--> Ax
by iterables = Map (iter, iterables) while
Iterables:
yield Tuple (Map (Next, Iterables))
Izip_longest (Iter1, Iter2, ... itern, [Fillvalue=none]):
the same as Izip (), but the iterative process lasts until all input iteration variables iter1,iter2 are exhausted, and none is used to populate the values of the iteration variables that are already in use if you do not specify a different value using the Fillvalue keyword parameter.
def izip_longest (*args, **kwds):
# izip_longest (' ABCD ', ' xy ', fillvalue= '-')--> Ax by c-d-
fillvalue = KWDS.G ET (' Fillvalue ')
def sentinel (counter = ([Fillvalue]* (Len (args)-1). Pop): Yield counter
() # yields the Fillvalue, or raises indexerror
fillers = repeat (fillvalue)
iters = [Chain (it, Sentinel (), fillers) for it in AR GS]
try: For
tup in Izip (*iters):
yield tup except Indexerror
:
Pass
Permutations (iterable [, R]):
Creates an iterator that returns a sequence of all items in the iterable that have a length of R, and if R is omitted, the length of the sequence is the same as the number of items in the iterable:
def permutations (iterable, R=none):
# permutations (' ABCD ', 2)--> AB AC AD BA BC BD CA CB CD DA DB DC
# Permuta tions (range (3))--> 012 021 102-201 210
pool = tuple (iterable)
n = len (pool)
R = N if R is None else r< C6/>if r > N:
return
indices = range (n)
cycles = Range (n, n-r,-1)
yield tuple (pool[i to I in Indice S[:R] While
N: to
I in reversed (range (r)):
cycles[i] = 1
if cycles[i] = = 0:
indices[i:] = ind Ices[i+1:] + indices[i:i+1]
cycles[i] = n-i
else:
j = cycles[i]
indices[i], indices[-j] = indices[- J], Indices[i]
yield tuple (pool[i] for i-indices[:r])
break
else:
return
Product (Iter1, Iter2, ... itern, [repeat=1]):
Creates an iterator that generates a item1,item2 of the Cartesian product of an item in, such as a repeat, is a keyword parameter that specifies the number of times a sequence is generated repeatedly.
def product (*args, **kwds):
# product (' ABCD ', ' xy ')--> Ax Ay Bx by Cx Cy Dx Dy
# Product (range (2), repeat=3)- -> 001 010 011
pools = map (tuple, args) * kwds.get (' repeat ', 1) result
= [[]] for
pool In pools: result
= [x+[y] for x in result for y in pool] for
prod in:
yield tuple (prod)
Repeat (Object [, Times]):
creates an iterator that repeats the build object,times (if provided) specifies a repeat count, and returns the object if no times is supplied.
def repeat (object, times=none):
# Repeat (3)-->
if is None: "While
True:
yield ob Ject
Else: for
i in Xrange (times):
yield Object
Starmap (func [, iterable]):
creates an iterator that generates the value func (*item), where item comes from iterable, which is valid only if the iterable generated item is applicable to the way the function is invoked.
Def starmap (function, iterable):
# Starmap (POW, [(2,5), (3,2), (10,3)])--> 9 1000 for
args in iterable:
yield function (*args)
TakeWhile (predicate [, iterable]):
creates an iterator that generates an entry in iterable that predicate (item) is true, and the iteration stops immediately if predicate evaluates to False.
def takewhile (predicate, iterable):
# takewhile (Lambda x:x<5, [1,4,6,4,1])--> 1 4 for
x in iterable:
i F predicate (x):
yield x
else:
break
Tee (iterable [, n]):
creates n-independent iterators from Iterable, and the created iterators are returned in N-tuple form, the default value of N is 2, and this function applies to any object that can be iterated, but in order to clone the original iterator, the generated items are cached and used in all newly created iterators, and you must be aware that Do not use the original iterator iterable after calling tee (), otherwise the caching mechanism may not work correctly.
def tee (iterable, n=2):
it = iter (iterable)
deques = [Collections.deque () for I in range (n)]
def gen (Mydeque) : While
True:
If not mydeque: # when the local deque is empty
newval = Next (IT) # Fetch a new value a D for
D in deques: # Load it to all ' deques
d.append (newval)
yield mydeque.popleft () return
tu Ple (Gen (d) for D-deques)
#Once Tee () has made a split, the original iterable the not is should anywhere else; used Erwise, the iterable could get advanced without the tee objects being
.
#This Itertool may require significant auxiliary storage (depending in how much temporary the data needs to be stored).
In general, if one iterator uses most or all of the data before another iterator, it's starts to use list () faster D of Tee ().
It is believed that this article has certain reference value to everyone's study of Python programming.