본문 바로가기
Python

[Python] reduce() 함수

by 기리의 개발로그 2024. 2. 5.

reduce 함수

reduce 함수 는 반복 가능한 객체(iterable object) 내 각 요소를 연산한 뒤 이전 연산 결과들과 누적해서 반환해 주는 함수이다.

from functolls import reduce

reduce(function, iterable)
  • function : 연산을 적용시킬 함수
  • iterable : 반복 가능한 자료(리스트, 튜플 등)

파이썬3부터는 reduce가 내장 함수가 아니기 때문에 functools 모듈에서 reduce 함수를 불러와야 한다.


reduce 함수를 사용하지 않을 때와 사용할 때의 소스를 확인해보자.

  • for 문 이용
def SumFunction(x, y):
    return x + y

target = list(range(1, 21))
result = 0
for value in target:
    result = SumFunction(result, value)
print(result) 
210

  • reduce 함수 이용
from functools import reduce

def SumFunction(x, y):
    return x + y

target = list(range(1, 21))
print(reduce(SumFunction, target)) 
210

reduce 함수 예제


from functools import reduce

def get_larger_value(a, b):    
    if a > b:        
        return a    
    else:        
        return b 

result = reduce(get_larger_value, [1,6,3,0])
print(result)
6

일반적인 함수뿐만 아니라 람다함수와 함께 사용할 수 있다.

from functools import reduce

target = list(range(1, 21))
print(reduce(lambda x, y: x + y, target))
210

from functools import reduce

f = lambda x, y: 3*x+2*y

result = reduce(f, [1,2,3])
print(result)
27
반응형

'Python' 카테고리의 다른 글

[Python] gcd(), lcm() 함수  (129) 2024.02.07
[Python] ceil(), floor() 함수  (114) 2024.02.06
[Python] eval() 함수  (142) 2024.01.26
[Python] ord(), chr() 함수  (162) 2024.01.25
[Python] all(), any() 함수  (147) 2024.01.23

댓글