开发者

Pythonic way to emulate itertools.product in python 2.4

I have a python 3 script that uses itertools.product, but I need to be able to run it on a machine that only has python 2.4 installed. Since itertools.product is new in python 2.6, I no longer have access to this function.

How can I emulate itertools.product in Python 2.4 i开发者_开发百科n a pythonic way?


Equivalent code from 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)


I'm not too familiar with python 2.4, but per the 2.7 docs:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜