Pythonic在python 2.4中模拟itertools.product的方法

Dan*_*Dan 3 python python-2.4 python-itertools

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

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

Jam*_*ong 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)
Run Code Online (Sandbox Code Playgroud)


Ada*_*ner 5

我不太熟悉python 2.4,但是按照2.7文档:

此函数等效于以下代码,但实际实现不会在内存中构建中间结果:

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)
Run Code Online (Sandbox Code Playgroud)