编程语言
首页 > 编程语言> > Pythonic在python 2.4中模拟itertools.product的方法

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

作者:互联网

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

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

解决方法:

我不太熟悉python 2.4,但是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)

标签:python,itertools,python-2-4
来源: https://codeday.me/bug/20190716/1482075.html