본문 바로가기
data science/python

lambda, map, filter, reduce

by 꼰대코더 2025. 1. 25.

lambda

 함수를 고정으로 정의해 놓지 않고 필요시에 간단한 형식으로 실행하는 무명함수

lambda 파라미터1, 파라미터2, ... : 연산 (파라미터1....)

def adder(a, b):
     return a + b

adder_lambda = lambda a, b: a + b
def to_upper(s):
      return s.upper()
to_upper_lambda = lambda s: s.upper()

 

프로그래밍을 편의를 위해 미리 정의해 둔 함수들 (map, filter, reduce)

map 

map(function_to_apply, list_of_inputs)

입력값의 수 = 처리후의 값의 수

items = [1, 2, 3, 4, 5]
squared = []

for i in items:
    squared.append(i**2)

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

 

filter

filter(조건 검사 함수(true만 출력), list_of_inputs)

입력값의 수 >= 처리후의 값의 수

number_list = range(-5, 5)
less_than_zero  = []

for i in number_list  :
   if i < 0:
      less_than_zero.append(i)

number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))

 

reduce

reduce(각값들을 앞의 연산결과 값과 다시 연산 , list_of_inputs)

처리후의 값의 수 = 1

product = 1
list = [1, 2, 3, 4]

for num in list:
    product = product * num

product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# 1, 2 -> 1 x 2 = 2
# 2, 3 -> 2 x 3 = 6
# 6, 4 -> 6 x 4 = 24

# Output: product = 24