ν”„λ‘œκ·Έλž˜λ° μ–Έμ–΄/Python

파이썬 map, filter ν•¨μˆ˜(with. iterator)

μ„œμ•„λž‘πŸ˜ 2023. 12. 17. 18:21

 

 

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 ν•¨μˆ˜μ— λŒ€ν•΄ μ•Œμ•„λ³΄κ² μŠ΅λ‹ˆλ‹€.

  1. map ν•¨μˆ˜:
    • map ν•¨μˆ˜λŠ” iterable의 각 μš”μ†Œμ— ν•¨μˆ˜λ₯Ό μ μš©ν•˜μ—¬ μƒˆλ‘œμš΄ iterable을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
    • ꡬ문: map(function, iterable)
    예제:
    # 각 숫자λ₯Ό μ œκ³±ν•˜λŠ” 예제 
    numbers = [1, 2, 3, 4, 5] 
    squared = map(lambda x: x**2, numbers) 
    print(list(squared))​



  2. 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))

 

 

μ΄λŸ¬ν•œ ν•¨μˆ˜λ“€μ€ 파이썬의 ν•¨μˆ˜ν˜• ν”„λ‘œκ·Έλž˜λ° μŠ€νƒ€μΌμ„ μ§€μ›ν•˜λ©°, μ½”λ“œλ₯Ό κ°„κ²°ν•˜κ²Œ μž‘μ„±ν•  수 μžˆλ„λ‘ λ„μ™€μ€λ‹ˆλ‹€. ν•¨μˆ˜ν˜• ν”„λ‘œκ·Έλž˜λ°μ€ μž…λ ₯κ³Ό 좜λ ₯ κ°„μ˜ 관계λ₯Ό κ°•μ‘°ν•˜κ³ , μƒνƒœ 변경을 ν”Όν•˜λ €λŠ” νŒ¨λŸ¬λ‹€μž„ 쀑 ν•˜λ‚˜μž…λ‹ˆλ‹€.