连少华

Python 计算笛卡尔积

计算多个集合的笛卡尔积,有规律可循,算法和代码也不难,但是很多语言都没有提供直接计算笛卡尔积的方法,需要自己写大段大段的代码计算笛卡尔积,python 提供了一种最简单的计算笛卡称积的方法(只需要一行代码),详见下面的代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @file   : Cartesian.py
# @author : shlian
# @date   : 2018/5/29
# @version: 1.0
# @desc   : 用python实现求笛卡尔积
import itertools

class cartesian(object):
    def __init__(self):
        self._data_list=[]

    def add_data(self,data=[]): #添加生成笛卡尔积的数据列表
        self._data_list.append(data)

    def build(self): #计算笛卡尔积
        for item in itertools.product(*self._data_list):
            print(item)

if __name__=="__main__":
    car=cartesian()
    car.add_data([1,2,3,4])
    car.add_data([5,6,7,8])
    car.add_data([9,10,11,12])
    car.build()

计算的结果如下:

(1, 5, 9)
(1, 5, 10)
(1, 5, 11)
(1, 5, 12)
(1, 6, 9)
(1, 6, 10)
(1, 6, 11)
(1, 6, 12)
(1, 7, 9)
(1, 7, 10)
(1, 7, 11)
(1, 7, 12)
(1, 8, 9)
(1, 8, 10)
(1, 8, 11)
(1, 8, 12)
(2, 5, 9)
(2, 5, 10)
(2, 5, 11)
(2, 5, 12)
(2, 6, 9)
(2, 6, 10)
(2, 6, 11)
(2, 6, 12)
(2, 7, 9)
(2, 7, 10)
(2, 7, 11)
(2, 7, 12)
(2, 8, 9)
(2, 8, 10)
(2, 8, 11)
(2, 8, 12)
(3, 5, 9)
(3, 5, 10)
(3, 5, 11)
(3, 5, 12)
(3, 6, 9)
(3, 6, 10)
(3, 6, 11)
(3, 6, 12)
(3, 7, 9)
(3, 7, 10)
(3, 7, 11)
(3, 7, 12)
(3, 8, 9)
(3, 8, 10)
(3, 8, 11)
(3, 8, 12)
(4, 5, 9)
(4, 5, 10)
(4, 5, 11)
(4, 5, 12)
(4, 6, 9)
(4, 6, 10)
(4, 6, 11)
(4, 6, 12)
(4, 7, 9)
(4, 7, 10)
(4, 7, 11)
(4, 7, 12)
(4, 8, 9)
(4, 8, 10)
(4, 8, 11)
(4, 8, 12)