| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- 715. Range Module
- 109. Convert Sorted List to Binary Search Tree
- 프로그래머스
- concurrency
- attribute
- Python Code
- 315. Count of Smaller Numbers After Self
- iterator
- shiba
- Python
- Convert Sorted List to Binary Search Tree
- 파이썬
- DWG
- 시바견
- Protocol
- LeetCode
- kaggle
- Generator
- 컴퓨터의 구조
- Class
- Python Implementation
- 밴픽
- Decorator
- Regular Expression
- Substring with Concatenation of All Words
- t1
- 43. Multiply Strings
- data science
- 30. Substring with Concatenation of All Words
- 운영체제
Archives
- Today
- Total
Scribbling
<Python> Iterator, Generator 본문
1. Iterator
__iter__, __next__를 가진 객체를 iterator protocol을 지원한다고 일컫는다.
class Counter:
def __init__(self, limit):
self.num = 0
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.num < self.limit:
ret = self.num
self.num += 1
return ret
else:
raise StopIteration
for i in Counter(10):
print(i, end=' ')
클래스에서 __getitem__ 메서드만 구현해도 이터레이터가 된다.
class Counter:
def __init__(self, limit):
self.num = 0
self.limit = limit
def __getitem__(self, index):
if index < self.limit:
return index * 3
else:
raise IndexError
for i in Counter(10):
print(i, end=' ')
2. Generator
Generator는 Iterator와 유사하나 yield를 사용하여 구현한다.
def generator(count):
list = [1, 2, 3, 4, 5]
t = 0
while t < count:
yield list[t % len(list)]
t += 1
g = generator(53)
for i in g:
print(i, end=' ')
yield from은 반복가능한 객체 / 이터레이터 / 제너레이터 객체 등에 사용 가능하다.
def generator():
list = [1, 2, 3, 4, 5]
yield from list
g = generator()
for i in g:
print(i, end=' ')'Computer Science > Python' 카테고리의 다른 글
| <Python> 정규표현식 (0) | 2021.11.09 |
|---|---|
| <Python> Decorator (0) | 2021.11.09 |
| <Python> Class 파헤치기 (0) | 2021.10.28 |
| <Python> 클로저 (0) | 2021.10.28 |
| 기본 자료구조 / 알고리즘 정리 (0) | 2021.08.16 |