Detailed explanation of the method of finding Cartesian product in Python

巴扎黑
Release: 2017-09-18 10:19:17
Original
4151 people have browsed it

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,
Copy after login

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 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template