https://docs.python.org/3/library/itertools.html#itertools.product
itertools
— Functions creating iterators for efficient looping
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.
The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.
For instance, SML provides a tabulation tool: tabulate(f)
which produces a sequence f(0), f(1), ...
. The same effect can be achieved in Python by combining map()
and count()
to form map(f, count())
.
These tools and their built-in counterparts also work well with the high-speed functions in the operator
module. For example, the multiplication operator can be mapped across two vectors to form an efficient dot-product: sum(map(operator.mul, vector1, vector2))
.
Infinite iterators:
Iterator | Arguments | Results | Example |
---|---|---|---|
start, [step] | start, start+step, start+2*step, … |
| |
p | p0, p1, … plast, p0, p1, … |
| |
elem [,n] | elem, elem, elem, … endlessly or up to n times |
|
Iterators terminating on the shortest input sequence:
Iterator | Arguments | Results | Example |
---|---|---|---|
p [,func] | p0, p0+p1, p0+p1+p2, … |
| |
p, q, … | p0, p1, … plast, q0, q1, … |
| |
iterable | p0, p1, … plast, q0, q1, … |
| |
data, selectors | (d[0] if s[0]), (d[1] if s[1]), … |
| |
pred, seq | seq[n], seq[n+1], starting when pred fails |
| |
pred, seq | elements of seq where pred(elem) is false |
| |
iterable[, key] | sub-iterators grouped by value of key(v) | ||
seq, [start,] stop [, step] | elements from seq[start:stop:step] |
| |
func, seq | func(*seq[0]), func(*seq[1]), … |
| |
pred, seq | seq[0], seq[1], until pred fails |
| |
it, n | it1, it2, … itn splits one iterator into n | ||
p, q, … | (p[0], q[0]), (p[1], q[1]), … |
|
Combinatoric iterators:
Iterator | Arguments | Results |
---|---|---|
p, q, … [repeat=1] | cartesian product, equivalent to a nested for-loop | |
p[, r] | r-length tuples, all possible orderings, no repeated elements | |
p, r | r-length tuples, in sorted order, no repeated elements | |
p, r | r-length tuples, in sorted order, with repeated elements |
Examples | Results |
---|---|
|
|
|
|
|
|
|
|
Itertool functions
The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream.
itertools.
accumulate
(iterable[, func, *, initial=None])Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).
If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including
Decimal
orFraction
.)Usually, the number of elements output matches the input iterable. However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.
Roughly equivalent to:
There are a number of uses for the func argument. It can be set to
min()
for a running minimum,max()
for a running maximum, oroperator.mul()
for a running product. Amortization tables can be built by accumulating interest and applying payments. First-order recurrence relations can be modeled by supplying the initial value in the iterable and using only the accumulated total in func argument:See
functools.reduce()
for a similar function that returns only the final accumulated value.New in version 3.2.
Changed in version 3.3: Added the optional func parameter.
Changed in version 3.8: Added the optional initial parameter.
itertools.
chain
(*iterables)Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:
- classmethod
chain.
from_iterable
(iterable) Alternate constructor for
chain()
. Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:
itertools.
combinations
(iterable, r)Return r length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.
Roughly equivalent to:
The code for
combinations()
can be also expressed as a subsequence ofpermutations()
after filtering entries where the elements are not in sorted order (according to their position in the input pool):The number of items returned is
n! / r! / (n-r)!
when0 <= r <= n
or zero whenr > n
.
itertools.
combinations_with_replacement
(iterable, r)Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.
Roughly equivalent to:
The code for
combinations_with_replacement()
can be also expressed as a subsequence ofproduct()
after filtering entries where the elements are not in sorted order (according to their position in the input pool):The number of items returned is
(n+r-1)! / r! / (n-1)!
whenn > 0
.New in version 3.1.
itertools.
compress
(data, selectors)Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to
True
. Stops when either the data or selectors iterables has been exhausted. Roughly equivalent to:New in version 3.1.
itertools.
count
(start=0, step=1)Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to
map()
to generate consecutive data points. Also, used withzip()
to add sequence numbers. Roughly equivalent to:When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as:
(start + step * i for i in count())
.Changed in version 3.1: Added step argument and allowed non-integer arguments.
itertools.
cycle
(iterable)Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).
itertools.
dropwhile
(predicate, iterable)Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Roughly equivalent to:
itertools.
filterfalse
(predicate, iterable)Make an iterator that filters elements from iterable returning only those for which the predicate is
False
. If predicate isNone
, return the items that are false. Roughly equivalent to:
itertools.
groupby
(iterable, key=None)Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is
None
, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.The operation of
groupby()
is similar to theuniq
filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.The returned group is itself an iterator that shares the underlying iterable with
groupby()
. Because the source is shared, when thegroupby()
object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:groupby()
is roughly equivalent to:
itertools.
islice
(iterable, stop)itertools.
islice
(iterable, start, stop[, step])Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is
None
, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing,islice()
does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Roughly equivalent to:If start is
None
, then iteration starts at zero. If step isNone
, then the step defaults to one.
itertools.
permutations
(iterable, r=None)Return successive r length permutations of elements in the iterable.
If r is not specified or is
None
, then r defaults to the length of the iterable and all possible full-length permutations are generated.Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.
Roughly equivalent to:
The code for
permutations()
can be also expressed as a subsequence ofproduct()
, filtered to exclude entries with repeated elements (those from the same position in the input pool):The number of items returned is
n! / (n-r)!
when0 <= r <= n
or zero whenr > n
.
itertools.
product
(*iterables, repeat=1)Cartesian product of input iterables.
Roughly equivalent to nested for-loops in a generator expression. For example,
product(A, B)
returns the same as((x,y) for x in A for y in B)
.The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.
To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example,
product(A, repeat=4)
means the same asproduct(A, A, A, A)
.This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:
itertools.
repeat
(object[, times])Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to
map()
for invariant parameters to the called function. Also used withzip()
to create an invariant part of a tuple record.Roughly equivalent to:
A common use for repeat is to supply a stream of constant values to map or zip:
itertools.
starmap
(function, iterable)Make an iterator that computes the function using arguments obtained from the iterable. Used instead of
map()
when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference betweenmap()
andstarmap()
parallels the distinction betweenfunction(a,b)
andfunction(*c)
. Roughly equivalent to:
itertools.
takewhile
(predicate, iterable)Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:
itertools.
tee
(iterable, n=2)Return n independent iterators from a single iterable.
The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue).
Roughly equivalent to:
Once
tee()
has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.tee
iterators are not threadsafe. ARuntimeError
may be raised when using simultaneously iterators returned by the sametee()
call, even if the original iterable is threadsafe.This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use
list()
instead oftee()
.
itertools.
zip_longest
(*iterables, fillvalue=None)Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:
If one of the iterables is potentially infinite, then the
zip_longest()
function should be wrapped with something that limits the number of calls (for exampleislice()
ortakewhile()
). If not specified, fillvalue defaults toNone
.
Itertools Recipes
This section shows recipes for creating an extended toolset using the existing itertools as building blocks.
Substantially all of these recipes and many, many others can be installed from the more-itertools project found on the Python Package Index:
The extended tools offer the same high performance as the underlying toolset. The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once. Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables. High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead.
'C Lang > Python Program Diary' 카테고리의 다른 글
iterator객체, for문 직접 만들어보기 (0) | 2019.11.06 |
---|---|
python template literal : f"somestring {variable}" (0) | 2019.11.01 |
python에서 변수나 리턴의 타입을 지정 : typing, NewType, generics, (0) | 2019.10.21 |
파이썬의 시간대에 대해 알아보기, naive datetime, aware datetime (0) | 2019.10.09 |
Adding Dates and Times in Python (0) | 2019.10.09 |