Python's built-in modules itertools
provide useful functions for manipulating iterative objects.
1,Infinite iterators
Iterator |
Arguments |
Results |
Example |
count () |
start, [step] |
start, Start+step, Start+2*step, ... |
count ( --> 10 11 12 < Span class= "Pre" >13 14 |
cycle () |
p |
p0, p1, ... plast, P0, p1, ... |
cycle (' ABCD ') < Span class= "Pre" >--> a b c d a b c d |
repeat()
|
Elem [, N] |
Elem, Elem, Elem, ... endlessly or up to n times |
repeat(10, 3) --> 10 10 10
|
1.1 Count
Creates an iterator that generates a sequential integer starting at N, and computes from 0 if n is omitted (note: This iterator does not support long integers)
If Sys.maxint is exceeded, the counter overflows and continues to be calculated from-sys.maxint-1.
>>> import itertools>>> n = itertools.count (1) >>> for I in N:print (i) 1234 ...
1.2 Cycle
Pass in a sequence and loop indefinitely:
>>> itertools.cycle (' ABCDE ') <itertools.cycle object at 0x00000000033576c8>>>> for I in Itertools.cycle (' ABCDE '):p rint (i) abcdeab .....
1.3 Repeat
Creates an iterator that repeats the build object,times (if provided) to specify a repeating count, and returns the object without a times.
2.iterators terminating on the shortest input sequence
Iterator |
Arguments |
Results |
Example |
accumulate()
|
p [, Func] |
P0, P0+P1, P0+P1+P2, ... |
accumulate([1,2,3,4,5]) --> 1 3 6 10 15
|
chain()
|
P, Q, ... |
P0, p1, ... plast, q0, Q1, ... |
chain(‘ABC‘, ‘DEF‘) --> A B C D E F
|
chain.from_iterable()
|
Iterable |
P0, p1, ... plast, q0, Q1, ... |
chain.from_iterable([‘ABC‘, ‘DEF‘]) --> A B C DE F
|
compress()
|
Data, selectors |
(D[0] If s[0]), (d[1] if s[1]), ... |
compress(‘ABCDEF‘, [1,0,1,0,1,1]) --> A C E F
|
dropwhile()
|
Pred, seq |
Seq[n], seq[n+1], starting when pred fails |
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
|
filterfalse()
|
Pred, seq |
Elements of Seq where pred (elem) is False |
filterfalse(lambda x: x%2, range(10)) --> 0 2 46 8
|
groupby()
|
iterable[, Keyfunc] |
Sub-iterators grouped by value of Keyfunc (v) |
|
islice()
|
Seq, [Start,] stop [, step] |
Elements from Seq[start:stop:step] |
islice(‘ABCDEFG‘, 2, None) --> C D E F G
|
starmap()
|
Func, SEQ |
Func (*seq[0]), func (*seq[1]), ... |
starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 91000
|
takewhile()
|
Pred, seq |
Seq[0], seq[1], until pred fails |
takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
|
tee()
|
it, n |
It1, it2, ... ITN splits one iterator into n |
|
zip_longest()
|
P, Q, ... |
(P[0], q[0]), (p[1], q[1]), ... |
zip_longest(‘ABCD‘, ‘xy‘, fillvalue=‘-‘) --> AxBy C- D-
|
2.1 Chain
Multiple iterators are used as parameters, but only a single iterator is returned, which produces the contents of all the parameter iterators as if they were from a single sequence.
>>> for C in Itertools.chain (' ABC ', ' XYZ '): ... Print (c) # Iteration effect: ' A ' B ' C ' ' X ' Y ' Z '
2.2 groupby
Returns an iterator that produces a collection of values grouped by key.
If iterable generates the same item in multiple successive iterations, a group is defined, and if the function is applied to a categorical list, then the grouping defines all the unique items in the list, and key (if provided) is a function that applies to each item if the function has a return value. The value will be used for subsequent entries instead of the item itself for comparison, and this function returns an iterator generating element (key, group), where key is a grouped key value, and group is an iterator that generates all the items that make up the group.
>>> for key, group in Itertools.groupby (' aaabbbccaaa '): ... Print (Key, List (group)) ... A [' A ', ' a ', ' a ']b [' B ', ' B ', ' B ']c [' C ', ' C ']a [' a ', ' a ', ' a ']
The selection rule is actually done by function, as long as the value returned by the two elements acting on the function is equal, the two elements are considered to be in a group, and the function returns the value as the key of the group. If we want to ignore the case grouping, we can let ‘A‘
the element and ‘a‘
both return the same key:
>>> for key, group in Itertools.groupby (' aaabbbccaaa ', Lambda C:c.upper ()): ... Print (Key, List (group)) ... A [' A ', ' a ', ' a ']b [' B ', ' B ', ' B ']c [' C ', ' C ']a [' a ', ' a ', ' a ']
3,combinatoric generators
Iterator |
Arguments |
Results |
product()
|
P, Q, ... [Repeat=1] |
Cartesian product, equivalent to a nested for-loop |
permutations()
|
p[, R] |
R-length tuples, all possible orderings, no repeated elements |
combinations()
|
P, R |
R-length tuples, in sorted order, no repeated elements |
combinations_with_replacement () |
p, R |
r-length tuples, in sorted order, with repeated elements |
product (' ABCD ', repeat=2) |
&NBSP; |
aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd |
permutations (' ABCD ', 2) |
&NBSP; |
ab ac ad ba bc bd ca cb cd da db DC |
combination S (' ABCD ', 2) |
|
Ab ac ad bc BD CD |
combinations_with_replacement(‘ABCD‘, 2)
|
|
AA AB AC AD BB BC BD CC CD DD
|
3.1 Product (*iterables[, repeat]) Cartesian product
Create an iterator that generates a item1,item2 of the Cartesian product for the items in the, etc., repeat is a keyword parameter that specifies the number of times the sequence is generated repeatedly.
>>> A = (All-in-A-Z) >>> B = (' A ', ' B ', ' C ') >>> C = Itertools.product (A, b) >>> for I in C:print (i) (1, ' A ') (1, ' B ') (1, ' C ') (2, ' A ') (2, ' B ') (2, ' C ') (3, ' A ') (3, ' B ') (3, ' C ')
3.2 Permutations (iterable[, R]) arrangement
Creates an iterator that returns a sequence of all items of length r in the Iterable, and if R is omitted, the length of the sequence is the same as the number of items in the iterable: Returns an iterator to the tuple with any r elements in P
>>> a = [1, 2, 3, 4]>>> s = [i-I in Itertools.permutations (a,3)] # Select 3 elements from sequence A to arrange >>> s[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3 , 1), (4, 3, 2)]>>> s_number = [i[0]*100 + i[1]*10 + i[2] for I in S]
3.3 Combinations (iterable, R) combination
Creates an iterator that returns all of the iterable in length R, and the items in the returned subsequence are sorted in the order of the input iterable (without duplicates)
>>> a = [1, 2, 3, 4]>>> s = [i-I in Itertools.combinations (a,2)] # select 2 non-repeating elements from sequence a >>> s[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
For more details, please visit our website: https://docs.python.org/3.5/library/itertools.html
Python3 's Itertools module