0

这部分程序有什么作用(在Nubela 的 guthub上找到)?

def product(*args, **kwds):
    """
    for py2.6< support (they lack itertools lib)
    - http://docs.python.org/2/library/itertools.html#itertools.permutations
    """
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

后来在程序中:

list(set((product(*[range(2) for _ in range(length)]))))
4

1 回答 1

1

它实现itertools.product了向后兼容。请参阅文档product

itertools.product(*iterables[, 重复])

输入迭代的笛卡尔积。

等效于生成器表达式中的嵌套 for 循环。例如,product(A, B) 返回与 ((x,y) for x in A for y in B) 相同的结果。

嵌套循环像里程表一样循环,每次迭代时最右边的元素都会前进。此模式创建一个字典顺序,以便如果输入的可迭代项已排序,则产品元组按排序顺序发出。

要计算可迭代对象与自身的乘积,请使用可选的 repeat 关键字参数指定重复次数。例如,product(A, repeat=4) 与 product(A, A, A, A) 的含义相同。

这个函数等价于下面的代码,只是实际的实现不会在内存中建立中间结果:

def product(*args, **kwds):
    # 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 = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

请注意文档中的代码如何与您找到的内容相匹配。

我不明白他们为什么在文档中引用itertools.permutations...代码:

list(set((product(*[range(2) for _ in range(length)]))))

AFAIK它相当于:

list(product(*[range(2) for _ in range(length)]))

它只是计算length range(2)迭代的乘积。

于 2013-03-23T16:49:08.883 回答