2011-10-11 3 views
3

itertools.product을 사용하는 python 3 스크립트가 있지만 파이썬 2.4 만 설치된 컴퓨터에서 실행할 수 있어야합니다. itertools.product이 파이썬 2.6에서 새롭기 때문에 더 이상이 함수에 액세스 할 수 없습니다.python에서 itertools.product를 에뮬레이션하는 Python 방법 2.4

파이썬 2.4에서 itertools.product을 파이썬 2.4로 에뮬레이션하려면 어떻게해야합니까?

답변

5

의 코드 만 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

등가 내가 파이썬 2.4 너무 익숙하지 않다 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)