반응형

map, filter, zip, reduce 함수와 람다(lambda)로 데이터 처리 흐름을 간결하게 만드는 방법을 예제 중심으로 정리했습니다.

1. map() — 각 요소에 함수 적용

nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares)  # [1, 4, 9, 16, 25]

map()은 리스트나 튜플 등 이터러블의 각 요소에 함수를 순차적으로 적용하여 새로운 맵 객체를 반환합니다

2. filter() — 조건에 맞는 요소 필터링

numbers = [1,2,3,4,5,6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6]

filter()는 각 요소에 조건함수를 적용하여 참인 값들만 추출합니다.

3. zip() — 여러 이터러블을 튜플로 묶기

a = [1,2,3]
b = ['a','b','c']
combined = list(zip(a, b))
print(combined)  # [(1,'a'), (2,'b'), (3,'c')]

zip()은 여러 이터러블을 병렬로 병합하여 튜플 시퀀스로 반환합니다.

4. reduce() — 누적 계산

from functools import reduce

nums = [2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product)  # 120

reduce()는 첫 두 요소부터 차례대로 누적하며 단일 값으로 압축합니다. functools 모듈에서 제공됩니다.

5. 조합 예제: filter + map + zip + reduce

from functools import reduce

names = ['Anna', 'Bob', 'Charlie', 'David']
ages = [24, 30, 18, 22]

# 나이 >20 이름과 나이 튜플 생성
pairs = list(zip(names, ages))
filtered = list(filter(lambda na: na[1] > 20, pairs))
formatted = list(map(lambda na: f"{na[0]}({na[1]})", filtered))
result = ", ".join(formatted)

print(result)  # e.g. "Anna(24), Bob(30), David(22)"

요약 및 다음 글 예고

  • map: 각 요소에 함수 적용
  • filter: 조건에 맞는 요소만 추출
  • zip: 여러 이터러블을 동시에 결합
  • reduce: 누적 계산으로 단일 값 생성

🎯 다음 글에서는 가상환경과 패키지 관리(venv, pip)에 대해 자세히 다룹니다!

728x90

+ Recent posts