python 제너레이터화
조회수 106회
from itertools import product
combis = []
for i in range(1,5):
for j in product([x for x in range(1,5)], repeat=i):
combis.append(j)
combis 를 루프 돌기
제너레이터화 시키지 못한 예시 코드는 상단과 같습니다.
이터툴스의 모듈들은 제너레이터니까, 그걸 잘 써보려고 했는데, 잘 안된단 말이죠.
결국 원하는 combis는 다음과 같습니다.
[1], [2], [3], ..[1,1], [1,2], [1,3],
...
[1,1,1], [1,1,2], [1,1,3]...[1,1,1,1], [1,1,1,2], ...
메모리를 쓸데없이 많이 먹습니다.
이걸 제너레이터로 쓰려면 어떡하면 될까요?
그러니까
def combi():
for i in range(1,5):
for j in product([x for x in range(1,5)], repeat=i):
yield(j)
이걸 안 만들어 주고, 있는 이터툴스를 이용해서 하는 방법을 찾습니다.
2 답변
-
참고해보세요.
import itertools as it gen = iter(lambda i=iter(range(1, 5)): list(it.product([x for x in range(1, 5)], repeat=next(i))), []) next(gen) [(1,), (2,), (3,), (4,)] next(gen) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
-
원하는게 맞는지 모르겠습니다.
리스트컴프리헨션 문법을 이용해 제너레이터를 만들었습니다.
from itertools import product combis = [] for i in range(1, 5): for j in product([x for x in range(1, 5)], repeat=i): combis.append(j) # print(combis) combis2 = [j for i in range(1, 5) for j in product([x for x in range(1, 5)], repeat=i)] for x, y in zip(combis, combis2): if x != y: print("diff") else: print("same") combis_gen = (j for i in range(1, 5) for j in product([x for x in range(1, 5)], repeat=i)) print(type(combis_gen)) combis_gen_listed = list(combis_gen) # print(combis_gen_listed) for x, y in zip(combis, combis_gen_listed): if x != y: print("diff") else: print("same")
댓글 입력