itertools模块中的product方法

itertools模块中的product方法

itertools.product(*iterables[, repeat])

笛卡尔积

创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。

代码如下:
1 def product(*args, **kwds):
2     # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
3     # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
4     pools = map(tuple, args) * kwds.get('repeat', 1)
5     result = [[]]
6     for pool in pools:
7         result = [x+[y] for x in result for y in pool]
8     for prod in result:
9         yield tuple(prod)

例子

代码如下:
 1 import itertools
 2 a = (1, 2, 3)
 3 b = ('A', 'B', 'C')
 4 c = itertools.product(a,b)
 5 for elem in c:
 6     print(elem)
 7 (1, 'A')
 8 (1, 'B')
 9 (1, 'C')
10 (2, 'A')
11 (2, 'B')
12 (2, 'C')
13 (3, 'A')
14 (3, 'B')
15 (3, 'C')

 

 

posted @ 2018-08-10 16:56  卉卉卉大爷  阅读(261)  评论(0编辑  收藏  举报