前言:学习本篇之前,先了解一下和permutations()函数,combinations()函数三者之间的区别。
python——combinations()函数_xiaofengdada的博客-CSDN博客
python——permutations()函数_xiaofengdada的博客-CSDN博客
一、概述
product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即:product(A, B) 和 ((x,y) for x in A for y in B)一样.
它的一般使用形式如下:
itertools.product(*iterables, repeat=1)
二、实例说明
(一)对列表获取多个无穷循环器的笛卡尔积
from itertools import product a = ['a','b','c'] b = [1,2,3] for i ,j in product(a,b): #对列表获取多个无穷循环器的笛卡尔积 print (i,j) print ('-----------------------------------------------------')
输出结果:
(二)对元组获取多个无穷循环器的笛卡尔积
from itertools import product c = ('e','f','g') d = (4,5,6) for i,j in product(c,d):#对元组获取多个无穷循环器的笛卡尔积 print (i,j) print ('-----------------------------------------------------')
输出结果:
(三)对字典获取多个无穷循环器的笛卡尔积
from itertools import product e = {'青鸟':'最美','世子':'纨绔'} j = {'xiaofeng':'1','废物':'2'}#对字典获取多个无穷循环器的笛卡尔积 for i,j in product(e,j): print (i,j) #字典只对键进行笛卡尔积交换 print ('-----------------------------------------------------')
输出结果: