이번 포스팅은 다음의 링크를 참조하였다.

리스트 컴프리헨션의 문제점

value = [len(x) for x in open("/tmp/my_file.txt")]
print(value)

>>>
[100, 57, 15, 1, 12, 75, 5, 86, 89, 11]

제너레이터 표현식

it = (len(x) for x in open("/tmp/my_file.txt"))
print(it)

>>>
<generator object <genexpr> at 0x101b81480>
print(next(it))
print(next(it))
  
>>>
100
57

다른 제너레이터 표현식과 연계

it = (len(x) for x in open("/tmp/my_file.txt"))
roots = ((x, x**0.5) for x in it)
print(next(roots))

>>>
(15, 3.872983346207417)

주의 사항

제너레이터란?

x = [1, 2, 3]
y = iter(x)
print(type(x))
print(type(y))
print(next(y))
print(next(y))
print(next(y))
print(next(y))

>>>
<type 'list'>
<type 'listiterator'>
1
2
3
Traceback (most recent call last):      # 마지막 정보를 호출한 이후에 next()를 호출하면 StopIteration 이라는 exception이 발생
  File "<stdin>", line 1, in <module>
StopIteration
def generator(n):
    i = 0
    while i < n:
        yield i
        i += 1

for x in generator(5):
    print x

>>>
0
1
2
3
4

지연 제너레이터란?

import time

def sleep_func(x):
    print ("sleep")
    time.sleep(1)
    return x
l = [sleep_func(x) for x in range(5)]

for i in l:
    print(i)

>>>
sleep
sleep
sleep
sleep
sleep
0
1
2
3
4
gen = (sleep_func(x) for x in range(5))

for i in gen:
    print(i)

>>>
sleep
0
sleep
1
sleep
2
sleep
3
sleep
4