본문 바로가기
C.W.K.
Stream
Lesson 06 of 07 · published

map·filter·any·all — 반복을 함수로 다루기

~15 min · map, filter, functional, comprehension

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

map과 filter가 하는 일

map(fn, items)은 각 원소를 함수로 바꾸고, filter(predicate, items)는 조건을 통과한 원소만 남겨. Python 3에서는 둘 다 필요한 순간에 값을 만드는 반복자를 돌려줘.

컴프리헨션이 더 잘 읽힐 때

짧은 lambda를 붙인 map/filter는 같은 내용을 컴프리헨션보다 멀리 떨어뜨려 읽게 해. 표현식과 조건이 간단하면 컴프리헨션이 보통 선명해. 반대로 str.upper처럼 이미 이름이 있는 함수를 그대로 적용한다면 map도 자연스러워.

any와 all은 일찍 멈춘다

any는 하나라도 참이면, all은 모두 참이면 참을 돌려줘. 답이 정해지는 순간 나머지를 읽지 않으므로 제너레이터 표현식과 잘 맞아. 빈 반복값에서 any는 거짓, all은 참이라는 논리적 정의도 기억해.

원칙: 같은 결과라면 변환과 조건이 한눈에 보이는 형태를 골라. 함수 이름이 이미 뜻을 말해 주면 map, 식 자체가 뜻이면 컴프리헨션이 대개 나아.

Code

map과 컴프리헨션 비교·python
nums = [1, 2, 3, 4, 5]

# functional 스타일
result = list(map(lambda x: x * 2, nums))
print(result)              # [2, 4, 6, 8, 10]

# 컴프리헨션 — 보통 더 명확
result = [x * 2 for x in nums]
print(result)              # [2, 4, 6, 8, 10]

# map 이 더 깔끔한 경우 — 함수가 이미 이름 있을 때
words = ["alpha", "beta", "gamma"]
upper = list(map(str.upper, words))      # 좀 더 좋아 보임
upper = [w.upper() for w in words]       # 이것도 OK
filter와 조건 있는 컴프리헨션 비교·python
nums = [-2, -1, 0, 1, 2]

# functional
positives = list(filter(lambda x: x > 0, nums))
print(positives)           # [1, 2]

# 컴프리헨션
positives = [x for x in nums if x > 0]
print(positives)           # [1, 2]

# 결합 — 컴프리헨션이 한 줄로
result = [x * 10 for x in nums if x > 0]
print(result)              # [10, 20]
일찍 답을 내는 any와 all·python
nums = [1, 2, 3, 4, 5]

# 음수 있나?
print(any(x < 0 for x in nums))      # False

# 모두 양수?
print(all(x > 0 for x in nums))      # True

# 둘 다 short-circuit — 결정 나는 첫 원소에서 멈춤
def expensive(x):
    print("checking", x)
    return x > 100

any(expensive(x) for x in [50, 150, 200])
# checking 50
# checking 150  <- 여기서 True 반환, 200 안 봄
Python 3의 map은 지연 반복자·python
result = map(str.upper, ["a", "b", "c"])
print(result)              # <map object at 0x...>
print(list(result))        # ['A', 'B', 'C']

# 소비된 후엔 빈 iterator
print(list(result))        # []

External links

Exercise

nums = [-3, -1, 0, 4, 7, 12]에서 map과 filter만 써 양수의 제곱 리스트를 만들어. 같은 결과를 컴프리헨션 한 줄로 다시 만들고, any로 10보다 큰 값이 있는지, all로 모든 값이 -5보다 큰지 확인해 네 결과를 출력해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.