Home >Backend Development >Python Tutorial >Detailed explanation of the method of finding Cartesian product in Python
This article mainly introduces the method of calculating the Cartesian product in Python, and analyzes the principles and implementation techniques of calculating the Cartesian product in Python in the form of examples. Friends in need can refer to the following
The examples in this article describe Python implements the method of finding Cartesian product. Share it with everyone for your reference, as follows:
In mathematics, the Cartesian product (Cartesian product) of two sets X and Y, also known as the direct product, is expressed as X × Y. The first The object is a member of X and the second object is a member of all possible ordered pairs of Y. Assume that set A={a,b} and set B={0,1,2}, then the Cartesian product of the two sets is {(a,0), (a,1), (a,2), ( b,0), (b,1), (b, 2)}. Sometimes we need to find the Cartesian product of two lists in Python. It is actually very simple and can be done with one line of code.
For example, find the Cartesian product of a={1,2,3} and b={0,1,2}, and the Cartesian product of a={1,2,3} itself, python The code is as follows:
#-*-coding:utf-8-*- import itertools; a=[1,2,3]; b=[4,5,6]; print "a,b的笛卡尔乘积:", for x in itertools.product(a,b): print x, print; print "a自身的笛卡尔乘积:", for x in itertools.product(a,a): print x,
The running result is as follows:
It is worth noting that the itertools here is not what I The tool I introduced is a python standard library, which can be used directly after importing it.
Just like the 15dfdae10d7c0c52b8c9b87fff3f31d0 header file in C language.
The above is the detailed content of Detailed explanation of the method of finding Cartesian product in Python. For more information, please follow other related articles on the PHP Chinese website!