티스토리 뷰
https://www.edwith.org/aipython/lecture/22955/
[LECTURE] Lambda & MapReduce : edwith
Pythonic Code - Lambda & MapReduce 학습 목표 함수처럼 사용가능한 익명함수인 Lambda, Sequence 자료형의 데이터에서 함수를 적용하는 방법... - 커넥트재단
www.edwith.org
위의 강의를 참조하여 만들었습니다.
lambda
general function
def f(x, y):
return x + y
print(f(1, 4))
Lambda function
f = lambda x, y: x+ y
print(f(1, 4))
f를 지정 안 한 Lambda function
print((lambda x: x + 1)(5))
< 6
map function
map(함수, 리스트) => 리스트의 각각의 원소에 함수가 적용된다.
ex = [1, 2, 3, 4, 5]
f = lambda x, y: x + y
print(list(map(f, ex, ex)))
map앞에 list를 빼도 작동이 됐지만, python 3 이후는 반드시 list를 붙여줘야한다. map만쓰면 위치만 출력된다. 즉, zip을 안쓰고 람다와 map을 사용해서도 이렇게 구현이 가능하다.
python 3에서는 list compresstion을 쓰는 것이 권장된다.
[value **2 for value in ex]
이런식으로 간단히 표현 가능 하기 때문이다. 그러나 위의 개념을 알아야한다.
아래와 같이 map을 for문으로도 사용 가능하다.
ex = [1,2,3,4,5]
f = lambda x: x ** 2
for i in map(f, ex):
print(i)
reduce function
map function과 달리 list에 똑같은 함수를 적용해서 통합(다른 것과 같이 보통 쓰인다.)
from functools import reduce
print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))
< 15
((((1+2) +3) +4) +5) = 15
1+2한 것에서 +3 한 것에다 +4 한 것에다 +5
+ 추우 판다스 할 때 유용하게 사용할 예정이다.
def factorial(n):
return reduce(
lambda x, y: x*y, range(1, n+1))
factorial(5)
< 120
결론) 코드의 직관성이 떨어져서 lambda나 reduce는 python3엣 사용을 권장하지 않는다. 그러나 다양한 머신러닝 코드에서 여전히 사용중이다.
'인공지능(Artificial Intelligence) > python' 카테고리의 다른 글
Data Structure_Collections (0) | 2020.07.11 |
---|---|
pythonic Code_Asterisk(*) (0) | 2020.07.10 |
pythonic Code_Enumerate, Zip (0) | 2020.07.09 |
pythonic Code_List Comprehension (0) | 2020.07.09 |
pythonic Code_split, Join (0) | 2020.07.09 |
- Total
- Today
- Yesterday
- 클라우데라
- react autoFocus
- error:0308010C:digital envelope routines::unsupported
- JavaScript
- Express
- react
- UserCreationForm
- TensorFlow
- next.config.js
- typescript
- Queue
- useState
- 자연어처리
- Python
- Deque
- pandas
- useHistory 안됨
- read_csv
- nextjs autoFocus
- login
- mongoDB
- vuejs
- logout
- django
- DFS
- nodejs
- NextJS
- BFS
- Vue
- 자료구조
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |