Kim Jinung

Python - reduce 본문

Language/Python

Python - reduce

Kim Jinung 2023. 2. 11. 15:24
 

functools — Higher-order functions and operations on callable objects

Source code: Lib/functools.py The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for t...

docs.python.org

Reduce 함수는 이터러블한 객체의 두 인자에, 함수를 누적 해서 적용할 때 사용할 수 있는 함수다. 리스트 [1, 2, 3]이 있을 때 두 인자에 덧셈이라는 함수를 누적 해서 적용하면

1 + 2 = 3

3 + 3 = 6

과 같이 진행된다. 이것이 reduce 함수의 동작이다.


Parameter

  • function: 누적합에 사용할 함수 ex) 덧셈, 곱셈, 뺄셈 등
  • iterable: 반복 가능한 자료구조
  • initializer: 초기 시작 값
def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

 

사용 예시

 

리스트의 누적합을 더하고자 하는 경우 다음과 같이 사용할 수 있다.

from functools import reduce

numbers = [1, 2, 3]

result = reduce(lambda x, y: x+y, numbers)

# result is 6

 

사용 예시2

 

리스트의 모든 요소를 누적 곱하고자 하는 경우 다음과 같이 사용할 수 있다.

initialzer 값을 이용해서 초기값이 2로 변경하는 경우 2 * 1 * 3 * 4가 되므로 결과는48이 된다.

numbers = [1, 2, 3, 4]

result1 = reduce(lambda x, y: x*y, numbers)

# result1 is 24

result2 = reduce(lambda x, y: x*y, numbers, 2)

# result2 is 48

'Language > Python' 카테고리의 다른 글

Python - functools.cmp_to_key (compare sort, 비교 정렬)  (0) 2023.01.19
Python - heapq  (0) 2022.12.08
Python - Counter  (0) 2022.12.06
Python - for/else  (0) 2022.12.02
Python - Regular Expression  (0) 2022.11.30