2011년 4월 19일 화요일

Python 제너레이터 재사용. (Reseting generator object)

참고: http://stackoverflow.com/questions/1271320/reseting-generator-object-in-python


# 문제. 

yield로 제너레이터를 만들어서 사용하고, 다시 사용할 필요가 있을때.. 
y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)
 


# 해결책

1) itertools.tee()

참조: http://docs.python.org/library/itertools.html#itertools.tee
y, y_backup = tee(FunctionWithYield())
for x in y: print(x)
for x in y_backup: print(x)

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().





2) list()

y = list(FunctionWithYield())
for x in y: print(x)
# can iterate again:
for x in y: print(x)


상황에 맞춰서 사용..

댓글 없음:

댓글 쓰기