What is Cartesian product

First of all, know what is Cartesian product, Baidu Encyclopedia explains it like this

Cartesian product refers to in mathematics, the Cartesian product (Cartesian product) of two sets X and Y, also known as direct product, expressed as X × Y, the first object is a member of X and the second object is Y A member of all possible pairs of .

Popular understanding is all combinations of all elements in one set and all elements in another set. Need to pay attention to the sequence.

for example:

集合A={a,b}, B={0,1,2}, the Cartesian product result is:

A×B={
    
    (a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}
B×A={
    
    (0, a), (0, b), (1, a), (1, b), (2, a), (2, b)}

Another example:

Set A is all initial consonants, and set B is all finals. Then the Cartesian product of set A and set B is all pinyin combinations.

Python default iterator library itertools provides Cartesian product calculation function product

usage:

itertools.product(*iterables, repeat=1)

Example 1:

Calculate all combinations of the surname "Zhang, Li" and the first name "One, Two, Three".

# -*- coding:utf-8 -*-
from itertools import product

x = ["张", "李"]
m = ["一", "二", "三"]

for p in product(x, m):
    print(p)

------------output----------------------
('张', '一')
('张', '二')
('张', '三')
('李', '一')
('李', '二')
('李', '三')

Example 2:

Of course, not just two collections, multiple collections are also possible.
Such as dictionary generation.

# -*- coding:utf-8 -*-
from itertools import product

for pw in product(["pass", "Pass"], ["word", "Word"], ["123", "456"]):
    print(pw)
------------output----------------------
('pass', 'word', '123')
('pass', 'word', '456')
('pass', 'Word', '123')
('pass', 'Word', '456')
('Pass', 'word', '123')
('Pass', 'word', '456')
('Pass', 'Word', '123')
('Pass', 'Word', '456')

Of course, if the dictionary generation does not need to be ordered, you can use the other two functions permutations
andcombinations

In [19]: list(permutations(["zhang", 3, '@'], 3))
Out[19]:
[('zhang', 3, '@'),
 ('zhang', '@', 3),
 (3, 'zhang', '@'),
 (3, '@', 'zhang'),
 ('@', 'zhang', 3),
 ('@', 3, 'zhang')]

In [20]: list(combinations(["zhang", 3, '@'], 3))
Out[20]: [('zhang', 3, '@')]

The difference between the two is that if the elements of several sets are the same, but the position order is different, they are permutationsrecorded as different sets, but combinationsthey are recorded as the same set

  • is permutationsan ordered set
  • for combinationsan unordered collection.

Guess you like

Origin blog.csdn.net/weixin_45277161/article/details/131528416