3

を使用するpython3スクリプトがitertools.productありますが、python2.4のみがインストールされているマシンで実行できる必要があります。itertools.productはPython2.6の新機能であるため、この関数にアクセスできなくなりました。

itertools.productPython 2.4でPythonの方法でエミュレートするにはどうすればよいですか?

4

2 に答える 2

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)
于 2011-10-11T20:36:28.610 に答える
5

私はPython2.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)
于 2011-10-11T20:37:20.987 に答える