繁体   English   中英

Python函数说明

[英]Python function explanation

程序的这部分做什么(在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)]))))

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

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

输入可迭代项的笛卡尔积。

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

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

要计算可迭代对象与其自身的乘积,请使用可选的repeat关键字参数指定重复次数。 例如,积(A,重复数= 4)表示与积(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)可迭代数的乘积。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM