- 주어진 배열에 있는 정수들 중에서 양수만 뽑아서 출력하는 함수 만들기
- map함수
def positive_list(a):
def positive(n):
return n>0
ans = list(map(positive, a))
return ans
positive_list([-1, 1, 2, -2, 3, -3])
[False, True, True, False, True, False]
def positive_list(a):
def positive(n):
return n>0
ans = list(filter(positive, a))
return ans
positive_list([-1, 1, 2, -2, 3, -3])
[1, 2, 3]
- 같은 구조로
map과 filter만 다르게 써봤다.
map 사용하니 배열에 대한 함수의 return값을 출력하는 것을 볼 수 있다.
filter 사용하니 배열에 대한 함수의 True 값만을 출력하는 것을 볼 수 있다.
Higher-Order Function
- 고차함수 또는 고계함수라고 부른다
- 함수를 다루는 함수이다.
- map함수와 filter함수는 파이썬의 고차함수중에 하나이다.
- 아래 두 조건을 만족하면 고차함수라고 할 수 있다.
- 하나 이상의 함수를 인자로 받는다.
- 한 수를 결과로 반환한다.
댓글