Python itertools模块中的product函数

product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即:

product(A, B) 和 ((x,y) for in for in B)一样.

它的一般使用形式如下:

itertools.product(*iterables, repeat=1)

iterables是可迭代对象,repeat指定iterable重复几次,即:

product(A,repeat=3)等价于product(A,A,A)

大概的实现逻辑如下(真正的内部实现不保存中间值):

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

 

原文地址:https://www.cnblogs.com/zywscq/p/10713390.html