In-depth understanding of iterators, Cartesian products, from itertools import product, novices can understand it at a glance

Insert image description here


1. product()What is it?

is a utility function provided by the built-in function that can calculate the Python中Cartesian product of multiple iterable objects. Accepts one or more iterable objects as arguments, then combines each of their elements to return a new iterator.product()itertoolsproduct()

2. product()Specific use cases

For example, suppose we have two iterables Aand B:

>>> A = [1, 2, 3]
>>> B = ['a', 'b']

We can product()calculate their Cartesian product using:

from itertools import product
C = list(product(A, B))
print(C)
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

Detailed code analysis

  1. Here, functions in the module are from itertools import productimported into the current namespace. We then call to compute the Cartesian product of the sum and convert it to a list usingitertoolsproduct()product(A, B)ABlist()
  2. We will notice that product()the result returned by the function is an iterator. If the amount of iteration is very large, you can use an iterator to avoid taking up a lot of memory without having to store it all in memory.
  3. product()The function can accept any number of iterable objects as arguments and compute their Cartesian product. If we have more than three iterables, we can use it like this product():
C = list(product(A, B, [1, 2]))
print(C)
[(1, 'a', 1), (1, 'a', 2), (1, 'b', 1), (1, 'b', 2), (2, 'a', 1), (2, 'a', 2), (2, 'b', 1), (2, 'b', 2), (3, 'a', 1), (3, 'a', 2), (3, 'b', 1), (3, 'b', 2)]

Here we pass in three iterable objects A, Band a list containing two elements [1, 2], and then calculate their Cartesian product.


Summarize

In short, product()the function is a very useful utility function that can conveniently calculate the Cartesian product of multiple iterable objects.

Guess you like

Origin blog.csdn.net/qlkaicx/article/details/131239657