[Python-Basic] lambda(익명함수) + map, reduce, filter

조상래·2021년 6월 8일
0

python

목록 보기
4/8

- def 키워드 없이 함수를 생성 주로 map, reduce, filter 인자 내에서 간단히 함수를 선언할 때 사용.

1. lambda(익명함수)

print((lambda x: x + 1)(1)) # 2

기본적인 형태는 'lamda 매개변수: 연산'이다. 그러나 익명함수 이기때문에 자체로는 재사용이 불가능하기 때문에 변수에 할당하면 def키워드를 사용하여 생성한 것과 같이 사용가능.

temp = lambda x: x + 1

print(temp(1)) # 2

2. map, reduce, filter

- map, reduce, filter와 사용하면 유용하다.

from functools import reduce

temp = [1, 2, 3, 4, 5, 6]

lambda_map = list(map(lambda x: x + 2, temp))

print(lambda_map) # [3, 4, 5, 6, 7, 8]

lambda_reduce = reduce(lambda x, y: x + y, temp, 1)

print(lambda_reduce) # 22

lambda_filter = list(filter(lambda x: x % 2 == 0, temp))

print(lambda_filter) # [2, 4, 6]
profile
Codestates Full IM26기 수료

0개의 댓글