2011-10-11 62 views
3

我有一个python 3脚本,使用itertools.product,但我需要能够在只安装了python 2.4的机器上运行它。由于itertools.product是python 2.6中的新功能,因此我无法再访问此功能。Python模拟itertools.product的pythonic方法2.4

如何在Python 2.4中以pythonic方式模拟itertools.product

回答

5

我不是太熟悉Python 2.4,但per the 2.7 docs

此功能相当于下面的代码,除了 实际执行不会在 内存中建立中间结果:

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) 
6

等效代码http://docs.python.org/library/itertools.html#itertools.product

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)