본문 바로가기
데이터분석/Python

map_reduce

by 버섯도리 2022. 1. 14.

# Map

 

 

=====================================================================

ex = [1, 2, 3, 4, 5]

f = lambda x: x ** 2

print(list(map(f, ex)))

---------------------------------------------------------------------

[1, 4, 9, 16, 25]

---------------------------------------------------------------------

 

 

=====================================================================

f = lambda x, y: x + y

print(list(map(f, ex, ex)))

---------------------------------------------------------------------

[[2, 4, 6, 8, 10]

---------------------------------------------------------------------

 

 

=====================================================================

res_list = list(map(

    lambda x: x ** 2 if x % 2 == 0 else x,

    ex))

print(res_list)

---------------------------------------------------------------------

[1, 4, 3, 16, 5]

---------------------------------------------------------------------

 

 

=====================================================================

#python 3에는 list를 꼭 붙여줘야 함

print(list(map(lambda x: x+x, ex)))

print((map(lambda x: x+x, ex)))

---------------------------------------------------------------------

[2, 4, 6, 8, 10]

<map object at 0x00000293745C2190>

---------------------------------------------------------------------

 

 

=====================================================================

ex = [1,2,3,4,5]

f = lambda x: x ** 2

print(list(map(f, ex)))

for i in map(f, ex):

    print(i)

result = map(f, ex)

print(next(result))

---------------------------------------------------------------------

[1, 4, 9, 16, 25]

1

4

9

16

25

1

---------------------------------------------------------------------

 

 

# Reduce

 

 

=====================================================================

from functools import reduce

print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))

---------------------------------------------------------------------

15

---------------------------------------------------------------------

 

 

=====================================================================

from functools import reduce

def factorial(n):

    return reduce(

            lambda x, y: x*y, range(1, n+1))

 

print(factorial(5))

---------------------------------------------------------------------

120

---------------------------------------------------------------------

 

 

 

 

 

 

 

참조 : http://www.boostcourse.org/ -> 머신러닝을 위한 파이썬

'데이터분석 > Python' 카테고리의 다른 글

defaultdict example  (0) 2022.01.14
deque example  (0) 2022.01.14
lambda_functon  (0) 2022.01.14
Titanic 실습  (0) 2022.01.14
Pandas example  (0) 2022.01.14