νμ΄μ¬ map, filter ν¨μ(with. iterator)
iterator(λ°λ³΅μ)
νμ΄μ¬μμ iterator(λ°λ³΅μ)λ μν κ°λ₯ν κ°μ²΄λ₯Ό λνλ΄λ κ°λ μ λλ€. Iteratorλ __iter__μ __next__ λ©μλλ₯Ό ꡬνν κ°μ²΄λ‘, __iter__λ μκΈ° μμ μ λ°ννκ³ , __next__λ λ€μ κ°μ λ°νν©λλ€. μ΄λ, λ μ΄μ λ°νν κ°μ΄ μμ λ StopIteration μμΈλ₯Ό λ°μμμΌ μνλ₯Ό μ’ λ£ν©λλ€.
μλ₯Ό λ€μ΄, κ°λ¨ν iteratorλ₯Ό ꡬνν΄λ³΄κ² μ΅λλ€
class MyIterator:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start >= self.end:
raise StopIteration
else:
self.start += 1
return self.start - 1
# μ¬μ© μμ
my_iter = MyIterator(1, 5)
for num in my_iter:
print(num)
mapκ³Ό filter
μ΄μ mapκ³Ό filter ν¨μμ λν΄ μμλ³΄κ² μ΅λλ€.
- map ν¨μ:
- map ν¨μλ iterableμ κ° μμμ ν¨μλ₯Ό μ μ©νμ¬ μλ‘μ΄ iterableμ λ°νν©λλ€.
- ꡬ문: map(function, iterable)
# κ° μ«μλ₯Ό μ κ³±νλ μμ numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x**2, numbers) print(list(squared))β
- filter ν¨μ:
- filter ν¨μλ iterableμ μμ μ€μμ 쑰건μ λ§μ‘±νλ μμλ§ λ¨κΈ°λ μν μ ν©λλ€.
- ꡬ문: filter(function, iterable)
# μ§μλ§ λ¨κΈ°λ μμ
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
μ΄λ¬ν ν¨μλ€μ νμ΄μ¬μ ν¨μν νλ‘κ·Έλλ° μ€νμΌμ μ§μνλ©°, μ½λλ₯Ό κ°κ²°νκ² μμ±ν μ μλλ‘ λμμ€λλ€. ν¨μν νλ‘κ·Έλλ°μ μ λ ₯κ³Ό μΆλ ₯ κ°μ κ΄κ³λ₯Ό κ°μ‘°νκ³ , μν λ³κ²½μ νΌνλ €λ ν¨λ¬λ€μ μ€ νλμ λλ€.