[Python]itertools.product函数


itertools.product(*iterables,repeat=1)

Cartesian product(笛卡尔乘积) of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example,product(A, B) returns the same as ((x,y) for x in A for y in B).

The nested loops cycle like an odometer with the rightmost element advancingon every iteration. This pattern creates a lexicographic ordering so that ifthe input's iterables are sorted, the product tuples are emitted in sortedorder.

To compute the product of an iterable with itself, specify the number ofrepetitions with the optionalrepeatkeyword argument. For example,product(A, repeat=4)means the same as product(A,A,A,A).

This function is roughly equivalent to the following code, except that theactual implementation does not build up intermediate results in memory:

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)

Before product() runs, it completely consumes the input iterables,keeping pools of values in memory to generate the products. Accordingly,it is only useful with finite inputs.

官方文档:

https://docs.python.org/3.10/library/itertools.html#itertools.product

猜你喜欢

转载自blog.csdn.net/weixin_66896881/article/details/128686696