Python built itertools module contains a set of functions used to generate different types or classes iterator is an iterator returns these functions, we can iterate the values for loop, you may be used next()
to value.
itertools iterator functions module provides the following types:
- Unlimited iterator: generating an infinite sequence of such a natural number sequence
1, 2, 3, 4, ...
; - Limited iterator: receiving one or more sequences (sequence) as a parameter, a combination, packet filtering and the like;
- Combiner: aligned sequences, combinations, and the like find sequence Cartesian product.
Unlimited iterator
itertools module provides three functions (in fact, they are the class) for generating an infinite sequence iterator:
-
count(firstval=0, step=1)
Create a starting firstval (default is 0), at STEP (default value = 1) in steps of infinite integer iterator
-
cycle(iterable)
iterable elements in the repeated cycle right, returns an iterator
-
repeat(object [,times]
Repeatedly generated object, if the given times, the number of repetitions times, otherwise unlimited
Combiners
itertools module also provides a plurality of combinations of function generators, used for obtaining the sequence of permutation and combination of:
- product
- permutations
- combinations
- combinations_with_replacement
product
product
For combining a plurality of required iterations may be an object, with its nested for loop equivalent. Its form is generally used as follows:
product(iter1, iter2, ... iterN, [repeat=1])
for item in itertools.product('abcd', 'xyz'): print(item)
The output is:
('a', 'x')
('a', 'y')
('a', 'z')
('b', 'x')
('b', 'y')
('b', 'z')
('c', 'x')
('c', 'y')
('c', 'z')
('d', 'x')
('d', 'y')
('d', 'z')
permutations
permutations
For generating a permutation, it is generally used in the form as follows:
permutations(iterable[, r])
Where, r element arranged to generate a specified length, if not specified, the default is the length element may iteration object.
list(permutations('ABC'))
The results are:
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
list(permutations('ABC', 2))
The results are:[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
combinations
combinations
Seeking for combining sequences, its use form is as follows:
combinations(iterable, r)
list(combinations('ABC', 2))
The results are:[('A', 'B'), ('A', 'C'), ('B', 'C')]
itertools module provides a number of functions for generating a plurality of types iterator whose return value is not List, but iterator.