제너레이터의 단점은 제너레이터를 단 한 번만 반복할 수 있다는 점이다. 만약 데이터를 여
러 번 반복해야 한다면 매번 제너레이터를 다시 만들거나 리스트를 사용해야 한다. 제너레
이터를 매번 생성하는 것이 너무 오래 걸린다면 리스트 사용을 추천한다.
또한 괄호 안에
for
문을 추가하는 방법으로도 제너레이터를 만들 수 있다.
evens
_
below
_
20 = (i for i in generate
_
range(20) if i % 2 == 0)
물론
for
나
next
를 통해서 반복문이 시작되기 전까지는 제너레이터가 생성되지
않는다. 이를 사용하여 정교한 데이터 처리 파이프라인을 만들 수 있다.
#
실제
반복문이
시작되기
전까지는
제너레이터가
생성되지
않는다
.
data = natural
_
numbers()
evens = (x for x in data if x % 2 == 0)
even
_
squares = (x ** 2 for x in evens)
even
_
squares
_
ending
_
in
_
six = (x for x in even
_
squares if x % 10 == 6)
#
등등
종종 리스트나 제너레이터에서 항목을 하나씩 확인해 볼 경우, 항목의 순서
(
index
)를 반환하고 싶을 때도 있다. 파이썬의
enumerate
함수를
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.