Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
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 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

나의 지식 보관소

파이썬 함수 map(), functools.reduce() 본문

프로그래밍 언어/파이썬

파이썬 함수 map(), functools.reduce()

야식은진리다 2021. 6. 6. 02:33

Map

map() 함수는 매개변수로 function과 iterable를 전달 받아 iterable의 모든 항목에 fuction을 적용한 후 그 결과를 이터레이터로 돌려줍니다. 만약 iterable 두개를 인자로 전달하면 function 또한 두개의 인자를 받아들여야합니다. 가장 짧은 iterable이 모두 소모되면 멈춥니다.

 

def multiply(x, y):
    return x * y


a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]

print(*map(multiply, a, b))
# 6 14 24 36 50
print(*map(lambda x, y: x + y, a, b))
# 7 9 11 13 15

 

Reduce

functools 모듈안에 있는 reduce() 함수는 map() 함수와 마찬가지로 fuction과 iterable를 전달받는데 reduce()는 왼쪽에서 오른쪽으로 iterable의 항목에 누적적으로 적용해서 iterable을 단일값으로 줄입니다. 예를 들어, reduce(lambdax,y:x+y,[1,2,3,4,5]) 는 ((((1+2)+3)+4)+5)로 계산됩니다. 여기서 람다의 x값은 누적값이고 y는 iterable에서 온 갱신값입니다. 만일 선택적 매개변수 initailizer가 있으면 계산에서 iterable항목의 맨 앞에 배치됩니다.

 

import functools


def multiply(x, y):
    return x * y


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

print(functools.reduce(multiply, a))
# 120
print(functools.reduce(multiply, a, 10))
# 1200